$.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);
}
});
- 运行 AJAX
- 运行 PHP,它会回显 GET 请求中 URL 的 HTML
- 将响应保存为 HTML 字符串
- 使用 jQuery 解析 HTML 字符串并替换所有链接和图像
- 在页面中显示
但基本上,更改尚未确定。
$(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");
});
大致意思是:
- 从
html
创建文档片段和 jQuery 对象 - 修改该对象中的任何
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/