2013-10-07 23 views
0

下面,我有一段javascript代碼。在javascript中的var修改問題

var htmlBlurb = '<div> hello <font color=red>world</font>!!!</div>'; 
$(htmlBlurb).find('font').each(function(e){ 
    $(this).html("Javascript"); 
}); 
console.log(htmlBlurb); 

我期待在htmlBlurb輸出作爲

<div> hello <font color=red>Javascript</font>!!!</div> 

htmlBlurb沒有改變。

有人可以解釋我在這裏錯過了什麼嗎?

+6

你永遠保存的'$結果(htmlBlurb)''來htmlBlurb',因此它只是一個字符串 –

+2

請不要使用''元素;它在一段時間前被棄用。 – j08691

+3

但他們用'' – AlienWebguy

回答

2

htmlBlurb是一個字符串。雖然$(htmlBlurb)創建了一個元素並臨時存儲它,但它不會修改原始字符串,就像$('a')上的運行操作不會修改字符串文字'a'一樣。

相反,做到以下幾點:

var htmlBlurb = '<div> hello <font color=red>world</font>!!!</div>'; 
var blurb=$(htmlBlurb) 
blurb.find('font').each(function(e){ 
    $(this).html("Javascript"); 
}); 
console.log(blurb.wrapAll('<div></div>').parent().html()); 
+0

我在控制檯中只看到Javascript。我試圖讓世界上的HTMLBlurb替換爲javascript – javaMan

+0

@javaMan修復,使用來自[這裏]的解決方案(http://stackoverflow.com/a/15663100/1198729) – Manishearth

+0

我只是看到這個 Javascript javaMan