替换XML问题
在检查了jQuery源代码后,我发现我遇到的问题是因为replaceWith
调用了html
文档不存在的html
。 replaceWith
不应该在XML文档上工作吗?
我发现这个公认的简单解决方法,以防将来有人需要它,这将完成我正在尝试做的事情:
xml.find('b').each(function() { $(this).replaceWith($('yo')) // this way you can custom taylor the XML based on each node's attributes and such });
但我仍然想知道为什么简单的方法不起作用。
我对jQuery了解不多,但不应该这样吗?
xml = $.parseXML('hey') $(xml).find('b').replaceWith('yo')
它代替yo
的xml
而不是代表 。 我做错什么了吗? 我正在使用jQuery 1.6.2。
编辑:
作为旁注,如果我尝试使用replaceWith
的函数版本,就像这样:
$(xml).find('b').replaceWith(function() { return 'yo' // doesn't matter what I return here })
我收到此错误:
TypeError: Cannot call method 'replace' of undefined
编辑2:
但是, replaceAll
有效,但我需要使用函数版本,所以我不能满足于此:
$('yo').replaceAll($(xml).find('b')) // works
编辑3:
这也有效:
xml.find('b').replaceWith($('yo')) // but not with the $() around the argument
这看起来像是对replaceWith()
的设计限制或bug。
当我跑:
$(xml).find('b').replaceWith(function() { return 'yo '; })
我得到一个"this[0].innerHTML is undefined"
exception。 看到这个jsFiddle 。
钻入xml
, b
节点没有innerHTML成员 – 这有点意义,因为它不是HTML。 ;)
所以,它看起来像replaceWith()
可能并不总是与XML很好。 考虑报告错误 。
是。 这是旧的bug,它仍然存在。 你可以解决它:
$.ajax dataType: "xml" ... success: (data) -> $(data).find("section").each -> ugly_but_working_clone = $($(".existing_dom_element").append(this).html())