Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/468.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用JQuery更改一个字符的颜色,而不更改HTML标记_Javascript_Jquery_Html_Dom_Dom Manipulation - Fatal编程技术网

Javascript 使用JQuery更改一个字符的颜色,而不更改HTML标记

Javascript 使用JQuery更改一个字符的颜色,而不更改HTML标记,javascript,jquery,html,dom,dom-manipulation,Javascript,Jquery,Html,Dom,Dom Manipulation,我试图使用JQuery遍历DOM,我想更改字母m的每个实例的颜色。这就是我到目前为止所做的: $(document).ready(function(){ var m = "<span style='color: red;'>m</span>" $("body").children().each(function() { $(this).html($(this).html().replace(/m/g, m)); }); }); 但那没用。同样,使

我试图使用JQuery遍历DOM,我想更改字母m的每个实例的颜色。这就是我到目前为止所做的:

$(document).ready(function(){
var m = "<span style='color: red;'>m</span>"

$("body").children().each(function() {
        $(this).html($(this).html().replace(/m/g, m));
   });
});

但那没用。同样,使用.text()而不是.html()对我来说也不起作用

要实现您想要的,您需要有一个递归函数。在该函数中,必须检查元素是否为文本节点。一旦有了文本节点,就可以替换它的内容。否则,您需要使用新元素调用相同的函数

此处所述功能:

letterScanner( $('body'), 'm' )

function letterScanner( $el, letter ){
  $el.contents().each( function(){
    if( this.nodeType == 3 ){
      $( this ).replaceWith( this.textContent.replace( new RegExp( '('+letter+'+)', 'g' ), "<span style='color: red;'>$1</span>" ) );
    }else{
        letterScanner( $( this ), letter )
    }
  } );
}
letterScanner($('body'),'m')
功能字母扫描器($el,字母){
$el.contents().each(函数()){
if(this.nodeType==3){
$(this.replaceWith)(this.textContent.replace(新的RegExp(“(“+字母+”),“g”),“$1”);
}否则{
字母扫描器($(本),字母)
}
} );
}
当然,要获得更好的性能,请更改最近父级的
正文
选择器


因此,只要您的所有文本都写在标记之间(而不是像某些奇怪的属性或css中那样),您就可以遍历所有文本节点并替换它们的内容。
letterScanner( $('body'), 'm' )

function letterScanner( $el, letter ){
  $el.contents().each( function(){
    if( this.nodeType == 3 ){
      $( this ).replaceWith( this.textContent.replace( new RegExp( '('+letter+'+)', 'g' ), "<span style='color: red;'>$1</span>" ) );
    }else{
        letterScanner( $( this ), letter )
    }
  } );
}