简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM