【发布时间】: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>')
});
});
【问题讨论】:
-
你的选择器说
select all <p> tags from .ce_text that are not <a> tag- 不合逻辑的选择器。 -
嘿,有逻辑选择器来解决我的问题吗?
-
Rejith R Krishnan 提供了一种使用 contents() filter() 来选择元素中的文本节点的工作方法:stackoverflow.com/a/37521803/3104330