6

检查 jQuery 源代码后,我发现我遇到的问题是因为XML 文档不存在replaceWith调用。htmlreplaceWith应该在 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
4

2 回答 2

2

这看起来像是设计限制replaceWith()或错误。

当我运行时:

$(xml).find('b').replaceWith(function() {
    return '<c>yo</c>';
})

我得到一个"this[0].innerHTML is undefined"例外。 看到这个 jsFiddle

深入xml研究,该b节点没有 innerHTML 成员——这有点道理,因为它不是 HTML。;)

因此,看起来replaceWith()可能并不总是与 XML 配合得很好。 考虑报告一个错误

于 2011-07-09T04:26:26.200 回答
0

是的。这是旧错误,它仍然存在。你可以解决它:

$.ajax
  dataType: "xml"
  ...
  success:  (data) ->
    $(data).find("section").each ->
      ugly_but_working_clone = $($(".existing_dom_element").append(this).html())
于 2012-05-21T16:54:17.380 回答