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

jQuery.attr() not updating the HTML string?

本文关键字:更新 HTML 字符串 attr jQuery      更新时间:2023-09-26
$.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 徽标作为源属性的片段,但

$(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());