【问题标题】:jQuery don't select a-tag in p-tagjQuery 不要在 p-tag 中选择 a-tag
【发布时间】:2016-05-30 08:21:52
【问题描述】:

您好,我尝试将 p-tag 中的数字样式设置为不同的样式,并阻止 a-tag 中的样式。 jQuery 将名为 number 的 span-tag 添加到 p-tag 中,但不应将其添加到 a-tag 的 href 中。

<div class="ce_text">
  <p>1234 example <a class="link" href="http://www.abc.de/123/def" target="_blank">www.abc.de/123/def</a> goes on 567.</p>
  <a href="http://www.999.com">Link 999 (no function)</a>
  <p>1234 example <a class="link" href="http://www.abc.de/123/def" target="_blank">www.abc.de/123/def</a> goes on 567.</p>
</div>

p-tag 中的数字应该包含 span-tag,a-tag 不应该:

RIGHT: <p><span="number">123</span>text goes here.</p>

WRONG: <a href="http://www.abc.de/<span class="number"123">123<span>/def">link</a>

我的方法行不通。

我的小提琴: https://jsfiddle.net/huppen/7f1ccvy5/6/

感谢任何解决我问题的提示。

使用 Rejith R Krishnan 的方法解决了问题(谢谢!):

$(".ce_text p").contents().filter(function(){ 
  return this.nodeType == 3; //nodeType 3 is the text nodes
}).each(function(i, v) {
    $(this).replaceWith(function(){
      return this.nodeValue.replace(/(\d+)/g, '<span class="number">$1</span>')
    });
});

Working JS-Fiddle

【问题讨论】:

  • 你的选择器说select all &lt;p&gt; tags from .ce_text that are not &lt;a&gt; tag - 不合逻辑的选择器。
  • 嘿,有逻辑选择器来解决我的问题吗?
  • Rejith R Krishnan 提供了一种使用 contents() filter() 来选择元素中的文本节点的工作方法:stackoverflow.com/a/37521803/3104330

标签: jquery replace children


【解决方案1】:

您可以使用这种方法。使用 contents()filter() 选择元素中的文本节点,然后用新的 HTML 替换它们。

$(".ce_text p").contents().filter(function(){ 
  return this.nodeType == 3; //nodeType 3 is the text nodes
}).each(function(i, v) {
    $(this).replaceWith(function(){
      return this.nodeValue.replace(/(\d+)/g, '<span class="number">$1</span>')
    });
});

DEMO

【讨论】:

  • 谢谢 Rejith R Krishnan,您的方法正在奏效 :-)
【解决方案2】:

您无法通过此查询选择器达到此目的,另一方面,您可以在 span 中创建 p 标记内的文本并在选择器中使用它。

Running Fiddle

【讨论】:

  • 感谢您的回答。我不想在所有 p 标签中手动设置 span 标签。有没有办法自动完成?
【解决方案3】:

试试这个解决方案。我在提琴手上进行了测试,它可以工作,但并不优雅:

$.each($('.ce_text p'), function(i, el){
    var txt = $(el).find("A").text();
    txt = txt.replace(/(\d+)/g, '<span class=number>$1</span>');
    txt = txt.substring(txt.indexOf("<span"));
    txt = txt.substring(0, txt.indexOf("</span>") + 7);

    $(el).find("A").after(txt);
    $(el).find("A").remove();
});

【讨论】:

  • 感谢您的方法。这将删除 a 标签,但它们应该保留。只应删除 a-tag 中的 span-tag。我猜这很棘手……
猜你喜欢
  • 1970-01-01
  • 2012-01-17
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 1970-01-01
相关资源
最近更新 更多