【问题标题】:Can't Modify Returned AJAX Variable无法修改返回的 AJAX 变量
【发布时间】:2011-01-31 21:57:04
【问题描述】:

我目前有以下 JavaScript/jQuery 脚本,它使用 AJAX 获取外部 html 页面并在其所有文本节点上运行一个函数。

$.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

【问题讨论】:

    标签: javascript ajax jquery


    【解决方案1】:

    $(html)和操作结果DOM树不能修改原始字符串。

    相反,你可以写

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

    通过将 HTML 包装在 &lt;div&gt; 中,我可以轻松检索完整源代码。

    我在博客上写了more detailed explanation

    【讨论】:

      猜你喜欢
      • 2014-03-01
      • 1970-01-01
      • 2011-04-09
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 2015-08-18
      相关资源
      最近更新 更多