2009-09-18 49 views
5

我想弄清楚如何用Javascript進行替換。我正在查看頁面的整個主體,並希望替換HTML標記內的關鍵字NOT。在JavaScript中,如何替換HTML頁面中的文本而不影響標籤?

下面是一個例子:

<body> 
    <span id="keyword">blah</span> 
    <div> 
    blah blah keyword blah<br /> 
    whatever keyword whatever 
    </div> 
</body> 

<script type="text/javascript"> 
var replace_terms = { 
    'keyword':{'url':'http://en.wikipedia.org/','target':'_blank'} 
} 

jQuery.each(replace_terms, function(i, val) { 
    var re = new RegExp(i, "gi"); 
    $('body').html(
    $('body').html().replace(re, '<a href="'+ val['url'] +'" target="'+val['target']+'">' + i + '</a>') 
); 
}); 

</script> 

我期待取代的「關鍵字」這不是一個HTML標籤內的所有實例(<>之間)。

我想我還需要忽略「關鍵字」是否在scriptstyle元素內。

+2

不會被定義爲整個網頁的HTML標記內? – 2009-09-18 12:59:53

+0

是的。我的例子中的HTML沒有通過。我基本上是指我不想替換標籤的任何屬性。 – Phil 2009-09-18 13:01:49

+1

我在想他是指在括號內(如屬性名稱/值)。 – Mayo 2009-09-18 13:01:51

回答

12

不要使用正則表達式來解析HTML。 [X] [HT] ML不是常規語言,不能可靠地使用正則表達式處理。您的瀏覽器內置了一個很好的HTML解析器;讓它能夠解決標籤在哪裏的問題。

此外,你也不想在身體上工作html()/innerHTML。這將對整個頁面進行序列化和重新解析,這將會很慢,並且會丟失HTML中無法序列化的任何信息,例如事件處理程序,表單值和其他JavaScript引用。

下面是使用DOM的方法,似乎爲我工作:

function replaceInElement(element, find, replace) { 
    // iterate over child nodes in reverse, as replacement may increase 
    // length of child node list. 
    for (var i= element.childNodes.length; i-->0;) { 
     var child= element.childNodes[i]; 
     if (child.nodeType==1) { // ELEMENT_NODE 
      var tag= child.nodeName.toLowerCase(); 
      if (tag!='style' && tag!='script') // special case, don't touch CDATA elements 
       replaceInElement(child, find, replace); 
     } else if (child.nodeType==3) { // TEXT_NODE 
      replaceInText(child, find, replace); 
     } 
    } 
} 
function replaceInText(text, find, replace) { 
    var match; 
    var matches= []; 
    while (match= find.exec(text.data)) 
     matches.push(match); 
    for (var i= matches.length; i-->0;) { 
     match= matches[i]; 
     text.splitText(match.index); 
     text.nextSibling.splitText(match[0].length); 
     text.parentNode.replaceChild(replace(match), text.nextSibling); 
    } 
} 

// keywords to match. This *must* be a 'g'lobal regexp or it'll fail bad 
var find= /\b(keyword|whatever)\b/gi; 

// replace matched strings with wiki links 
replaceInElement(document.body, find, function(match) { 
    var link= document.createElement('a'); 
    link.href= 'http://en.wikipedia.org/wiki/'+match[0]; 
    link.appendChild(document.createTextNode(match[0])); 
    return link; 
}); 
+1

'i - > 0'聰明。我以前從來沒有見過。 – 2009-09-18 14:40:08

+2

我不能聲稱這是一個C語言的反向迭代的成語! :-) – bobince 2009-09-18 14:47:20

+0

我通常只用'i - ',如:for(var i = 100; i--;)' – kangax 2009-09-18 16:18:02

相關問題