2013-01-13 68 views
-1

我正在嘗試在變量中保存一些HTML(來自XML文件),但不知何故,我收到了一些奇怪的錯誤。除此之外,即使我不使用它,瀏覽器似乎也會嘗試加載這段HTML代碼中使用的圖像。將HTML保存在變量中的JavaScript

下面的代碼:

// Load the data from the XML node. 
var description = $(this).find('description').text(); 

var descriptionWithTags = description.replace('<p>',''); 
descriptionWithTags = descriptionWithTags.replace('</p>','########'); 

// Remove HTML Tags and add the Line-Breaks 
var convertedString = $(descriptionWithTags).text(); 
convertedString = convertedString.replace('########','<br /><br />'); 
console.log("E"); 

// Save it in an array. 
contentRSS[articleCount] = convertedString; 

編輯:如果我刪除以下行,它再次工作,但我現在爲什麼不。

descriptionWithTags = descriptionWithTags.replace('<p>',''); 
+3

...,什麼是這些難以捉摸的'怪errors'? –

+0

它說jquery.js中有錯誤,但是顯示的是我加載的html內容的一部分。它看起來像是在混合一些東西。 –

回答

2

開始時你有沒有文字的HTML標籤:

var description = $(this).find('description').text(); // this removes HTML tags 

然後嘗試解析它作爲HTML:

var convertedString = $(descriptionWithTags).text(); 

這可不行。你或許應該在第一行用html:

var description = $(this).find('description').html(); 
+0

你好,謝謝你的回答。我不確定,但我想我需要第二個.text(),因爲它會去掉html標籤。第一個.text()只是刪除加載的競爭對象的。這是一個筆記樣本。 <![CDATA [一些HTML代碼在這裏。 ]]>

+0

問題主要在於第一個問題:您不能要求原始文本(從HTML標記中清除),然後要求將其解釋爲HTML。 –