您好,我尝试为p标签中的数字设置不同的样式,并防止a标签中的样式。 jQuery将称为数字的span标签添加到p标签,但不应将其添加到a标签的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标签中的数字应包含跨度标签,a标签不应:
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
最佳答案
您可以使用这种方法。使用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
关于jquery - jQuery不要在p标签中选择a标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37520883/