【发布时间】:2011-07-09 03:14:49
【问题描述】:
检查 jQuery 源代码后,我发现我遇到的问题是因为 replaceWith 调用了 XML 文档不存在的 html。 replaceWith 不应该在 XML 文档上工作吗?
我发现了这个公认的简单解决方法,以防将来有人需要它,这将完成我想要做的事情:
xml.find('b').each(function() {
$(this).replaceWith($('<c>yo</c>')) // this way you can custom taylor the XML based on each node's attributes and such
});
但我仍然想知道为什么简单的方法行不通。
我对 jQuery 了解不多,但这不应该有用吗?
xml = $.parseXML('<a><b>hey</b></a>')
$(xml).find('b').replaceWith('<c>yo</c>')
而不是xml 代表<a><c>yo</c></a> 它失败并代表<a></a>。我做错什么了吗?我正在使用 jQuery 1.6.2。
编辑:
附带说明,如果我尝试使用replaceWith 的函数版本,如下所示:
$(xml).find('b').replaceWith(function() {
return '<c>yo</c>' // doesn't matter what I return here
})
我收到此错误:
TypeError: Cannot call method 'replace' of undefined
编辑 2:
replaceAll 可以,但是我需要使用函数版本,所以我不能满足于此:
$('<c>yo</c>').replaceAll($(xml).find('b')) // works
编辑 3:
这也有效:
xml.find('b').replaceWith($('<c>yo</c>')) // but not with the $() around the argument
【问题讨论】:
标签: javascript jquery xml replacewith