2009-11-24 47 views
1

我的HTML代码包textnode:jQuery的:找到并与一些元素

<body>Firebrand will tend to burn any bricks out there. so the best idea is to ignore any active firebrand if you are a bricks. Otherwise, you can challenge a firebrand if you have the proper quality to keep up with their latest technology. And don't mess up with firebrand if you are a robber.</body> 

我想找到身体内的任何“火把”,并与<span class="firebrand">firebrand</span>与jQuery

更换
+0

请更清楚地表达你的意图。正如你可以在Karim79的回答中看到的那样,规范还不够清楚。 – Huppie 2009-11-24 09:46:06

+0

对不起我的坏, 我只想找到任何关键字,我希望用span来包裹无论父母的元素,它应该搜索整个文档。 我需要获取文本节点并用span展开,这样我可以给出不同的样式。 是否有无论如何我可以做到这一点,而不使用$(选择器).html()? – mdennisa 2009-11-24 14:35:08

回答

4

通过DOM只是递归,同时使用:

.replace(/(firebrand)/gi, '<span class="firebrand">$1</span>')

每个文本内容。

function firebrand($el) { 
    $el.contents().each(function() { 

     if (this.nodeType == 3) { // Text only 
      $(this).replaceWith($(this).text() 
       .replace(/(firebrand)/gi, '<span class="firebrand">$1</span>')); 
     } else { // Child element 
      firebrand($(this)); 
     } 

    }); 
} 

firebrand($("body")); 
+0

这帮我一把!谢谢! +1 – Thomas 2011-02-01 11:41:19

0

请尝试以下。

var textApply; 
textApply = function(node){ 
    jQuery.map($(node), function(node) { 
    var value = $(node)[0]; 
    if (value.nodeType == 3 && value.textContent.match(/firebrand/gi)) { 
     var foo = value.textContent.replace(/[\n\r\t ]+/,' ').replace(/firebrand/gi, '<span style="color:red">Firebrand</span>'); 
     var newitem = $(foo); 
     $(node).replaceWith(newitem); 
    } else if (value.nodeName != 'SCRIPT') { 
     jQuery.map($(node).contents(), textApply); 
    } 
    }); 
}; 
textApply($('body'));