gpt4 book ai didi

jQuery 不选择 p 标签中的 a 标签

转载 作者:行者123 更新时间:2023-12-01 04:41:07 26 4
gpt4 key购买 nike

您好,我尝试将 p 标签中的数字设置为不同的样式,并阻止 a 标签中的样式。 jQuery 将名为 number 的 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 标签中的数字应包含 span 标签,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>

我的方法行不通。

我的 fiddle : 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 不选择 p 标签中的 a 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37520883/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com