jQuery.attr()没有更新HTML字符串?

Vic*_*Vic 0 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);
    }
});
Run Code Online (Sandbox Code Playgroud)
  1. 运行AJAX
  2. 运行PHP,它在GET请求中回显URL的HTML
  3. 将响应保存为HTML字符串
  4. 使用jQuery解析HTML字符串并替换所有链接和图像
  5. 在页面中显示

但基本上,没有设置变化.

$(this).attr("src", "http://google.com/logo.jpg");
Run Code Online (Sandbox Code Playgroud)

返回带有google徽标的片段作为源属性,但是

$(this).replaceWith($(this).attr("src", "http://google.com/logo.jpg"));
Run Code Online (Sandbox Code Playgroud)

不行.

Pau*_*oub 7

这个:

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

手段,大致:

  1. 从中创建文档片段和jQuery对象 html
  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());
Run Code Online (Sandbox Code Playgroud)

虽然each()如果所有属性都相同,您可以跳过调用:

var d = $(html);

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

$('body').html(d.html());
Run Code Online (Sandbox Code Playgroud)