我目前有以下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
发布于 2011-01-21 02:02:05
编写$(html)和操作结果DOM树不能修改原始字符串。
相反,您可以编写
var content = $('<div>' + html + '</div>');
//Modify content
html = content.html();通过将超文本标记语言包装在<div>中,我可以轻松地检索完整的源代码。
我在我的博客上写了一个more detailed explanation。
https://stackoverflow.com/questions/4750703
复制相似问题