Can't Modify Returned AJAX Variable
I currently have the following JavaScript/jQuery script that gets an external html page using AJAX and runs a function on all it's text nodes.
$.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);
});
However although the logged new text node values have changed and are all correct, when I try to log the html at the end I just get what I started with, the original external webpage with none of the modifications in it.
What am I doing wrong?
DLiKS
Writing $(html)
and manipulating the results DOM tree cannot modify the original string.
Instead, you can write
var content = $('<div>' + html + '</div>');
//Modify content
html = content.html();
By wrapping the HTML in a <div>
, I can easily retrieve the full source.
I wrote a more detailed explanation on my blog.
精彩评论