Set*_*gie 6 javascript xml jquery replacewith
在检查了jQuery源代码之后,我发现我遇到的问题是因为XML文档不存在的replaceWith调用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
});
Run Code Online (Sandbox Code Playgroud)
但我仍然想知道为什么简单的方法不起作用.
我对jQuery了解不多,但不应该这样吗?
xml = $.parseXML('<a><b>hey</b></a>')
$(xml).find('b').replaceWith('<c>yo</c>')
Run Code Online (Sandbox Code Playgroud)
而不是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
})
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
TypeError: Cannot call method 'replace' of undefined
Run Code Online (Sandbox Code Playgroud)
编辑2:
replaceAll 然而,但我需要使用函数版本,所以我不能满足于此:
$('<c>yo</c>').replaceAll($(xml).find('b')) // works
Run Code Online (Sandbox Code Playgroud)
编辑3:
这也有效:
xml.find('b').replaceWith($('<c>yo</c>')) // but not with the $() around the argument
Run Code Online (Sandbox Code Playgroud)
这看起来要么是设计限制,replaceWith()要么是错误。
当我跑步时:
$(xml).find('b').replaceWith(function() {
return '<c>yo</c>';
})
Run Code Online (Sandbox Code Playgroud)
我有一个"this[0].innerHTML is undefined"例外。 请参阅这个 jsFiddle。
深入研究xml,该b节点没有innerHTML 成员——这有点道理,因为它不是HTML。;)
因此,看起来replaceWith()XML 并不总是能很好地发挥作用。 考虑报告错误。