2011-01-20 93 views
0

我目前有以下JavaScript/jQuery腳本,它使用AJAX獲取外部html頁面並在其所有文本節點上運行一個函數。不能修改返回的AJAX變量

$.get('webpage.html', function (html) { 
    $(html).find('*').each(function() { 
     $(this).contents().filter(function() { return this.nodeType === 3 }).each(function() { 
      this.nodeValue = foo(this.nodeValue); 
      console.log(this.nodeValue); 
     }); 
    console.log(html);      
}); 

然而,雖然記錄的新文本節點值發生了變化,是正確的,當我試圖在最後記錄的HTML我只得到什麼我開始用,用沒有修改的原外部網頁它。

我在做什麼錯?

DLiKS

回答

2

寫作$(html)和操縱的結果DOM樹不能修改原始字符串。

相反,你可以寫

var content = $('<div>' + html + '</div>'); 
//Modify content 
html = content.html(); 

通過在<div>包裝的HTML,我可以輕鬆地檢索完整的源代碼。我的博客寫了more detailed explanation