javascript - jQuery.attr() 不更新 HTML 字符串?

标签 javascript jquery

$.ajax({
    url: "getHTML.php",
    data: {url: "http://www.google.com"},
    success: function(e){
        var html = e;
        $('img', html).each(function(){
            $(this).attr("src", "http://google.com/logo.jpg");
        });
        $('a', html).each(function(){
            $(this).attr("href", "http://google.com/");
        });
        $('body').html(html);
    }
});
  1. 运行 AJAX
  2. 运行 PHP,它会回显 GET 请求中 URL 的 HTML
  3. 将响应保存为 HTML 字符串
  4. 使用 jQuery 解析 HTML 字符串并替换所有链接和图像
  5. 在页面中显示

但基本上,更改尚未确定。

$(this).attr("src", "http://google.com/logo.jpg");

返回以 google Logo 作为源属性的片段,但是

$(this).replaceWith($(this).attr("src", "http://google.com/logo.jpg"));

不起作用。

最佳答案

这个:

$('img', html).each(function(){
  $(this).attr("src", "http://google.com/logo.jpg");
});

大致意思是:

  1. html 创建文档片段和 jQuery 对象
  2. 修改该对象中的任何 img 标记

就是这样。您不存储该对象,因此您无法使用其更新的内容 - 并且不会(或应该)更改 html

尝试一下:

var d = $(html);

$('img', d).each(function() {
  $(this).attr("src", "http://google.com/logo.jpg");
});
$('a', d).each(function() {
  $(this).attr("href", "http://google.com/");
});
$('body').html(d.html());

尽管如果所有属性确实相同,您可以跳过 each() 调用:

var d = $(html);

$('img', d).attr("src",  "http://google.com/logo.jpg");
$('a',   d).attr("href", "http://google.com/");

$('body').html(d.html());

关于javascript - jQuery.attr() 不更新 HTML 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34800880/

相关文章:

javascript - 如何删除除一类之外的所有类

javascript - 转换 :unchecked to prop ('checked' , 错误)

jquery - jquery mobile 和 Phonegap 的大型数据库

javascript - OpenLayers 仅在鼠标移动结束后才具有重绘功能

javascript - 如何使用 taggingjs 避免空白初始化

javascript - 使用后退按钮或 Iron 路由后,Meteor 模板没有反应

javascript - 在 HTML 复选框上访问数组的键

javascript - jquery中动画未完成时如何阻止所有事件

javascript - 如何在本地机器上离线读写JSON?

javascript - 如何在页面上仅搜索具有特定类名的 div