2011-06-19 68 views
1

我有一個帶有單詞和定義的xml文件。字符串替換函數 - 如果替換,如何跳過?

 
<word definition="this is my definition">myWord</word>

當我的HTML頁面有myWord,我想改變myWord到鏈接與它的標題對我的詞的定義。

基本上就是這樣;

myWord變成

<a href="#" title="this is my definition">myWord </a>

要我使用這個代碼從XML鏈接。但是這個代碼鏈接了好幾次,甚至連定義的單詞也都鏈接了。所以我想檢查它是否已被鏈接,如果是的話,跳過。

 
x=xmlDoc.getElementsByTagName('word'); 
for (i=0;i' + x.item(i).attributes[0].textContent + ': ' + x.item(i).attributes[1].textContent + '\', this);" onMouseOut="doClear();">' +x[i].childNodes[0].nodeValue + ''; 
    replacer(text, linked);  

我有一個替代品的功能

 
function replacer(oldstring, newstring) { 
if(oldstring inside replaced tag) 
    { 
     //skip replacement 
    } 

else 
    { 
    document.body.innerHTML = document.body.innerHTML.replace(/oldstring/, newstring); 
    } 
} 


我想跳過更換,如果我的oldstring裏面

 
<span class="replaced">Replaced text</span>

我怎麼能寫如果這個代碼的部分。

我一直在爲此掙扎好幾天。請幫幫我! 提前致謝!

+7

你可能不希望在字符串層面上這樣做,因爲這是非常困難的解析HTML(你不能可靠地使用正則表達式來完成,例如,儘管很多人都嘗試過)。相反,我會將文本插入DOM元素(可以斷開連接,因此不顯示),然後循環遍歷文本節點,跳過不想處理的元素中的文本節點。相關參考資料:[DOM2 Core](http://www.w3.org/TR/DOM-Level-2-Core/),[DOM2 HTML](http://www.w3.org/TR/DOM- Level-2-HTML /),[DOM3 Core](http://www.w3.org/TR/DOM-Level-3-Core/) –

+0

請你告訴我該怎麼做! – testere

+0

恐怕我現在沒時間了,但上面的註釋中有參考資料的鏈接,下面是一個漫步DOM樹的例子:http://stackoverflow.com/questions/5158022/wrap-a -tags-around-http-text/5158204#5158204 –

回答

1

XSLT將執行此更好的辦法:

<?xml version="1.0"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:template match="*|@*|text()"> 
     <xsl:copy> 
      <xsl:apply-templates select="*|@*|text()"/> 
     </xsl:copy> 
    </xsl:template> 
    <xsl:template match="word"> 
     <a href="#" title="<xsl:copy-of select="data(@description)"/>"> 
      <xsl:copy-of select="data(.)"/></a> 
    </xsl:template> 
</xsl:stylesheet> 

聯繫我,如果任何細節需要