2009-11-24 90 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'));