jQuery不在p-tag中选择a-tag

jQuery不在p-tag中选择a-tag,jquery,replace,children,Jquery,Replace,Children,您好,我尝试在p-tag中设置不同的数字样式,并防止在a-tag中设置样式。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-tag中设置不同的数字样式,并防止在a-tag中设置样式。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标签中的数字应包含一个跨度标签,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>
我的方法行不通

我的小提琴:

任何能解决我问题的技巧都将不胜感激

用Rejith R Krishnan的方法解决了问题谢谢


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


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

$.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();
});

您可以使用这种方法。使用内容和过滤器选择元素中的文本节点,然后用新的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>')
    });
});

您的选择器说从.ce_文本中选择所有非标记的标记-不合逻辑的选择器。嘿,有没有一个逻辑选择器可以解决我的问题?Rejith R Krishnan提供了一种使用内容过滤器的工作方法来选择元素中的文本节点:谢谢您的回答。我不想在所有p标记中手动设置跨度标记。有没有一种方法可以自动完成?谢谢你的方法。这将删除a标签,但它们应该保留。仅应移除a标记内的跨度标记。我想这很棘手…谢谢你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>')
    });
});