replaceWith on XML problem

ⅰ亾dé卋堺 提交于 2019-12-09 17:50:19

问题


After examining the jQuery source, I see that the problem I am having is because replaceWith calls html which does not exist for XML documents. Is replaceWith not supposed to work on XML documents?

I have found this admittedly simple workaround, in case anybody needs it in the future, that will accomplish what I'm trying to do:

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
});

But I would still like to know why the easy way doesn't work.


I don't know much about jQuery, but shouldn't this work?

xml = $.parseXML('<a><b>hey</b></a>')
$(xml).find('b').replaceWith('<c>yo</c>')

Instead of xml representing <a><c>yo</c></a> it fails and represents <a></a>. Did I do something wrong? I am using jQuery 1.6.2.

Edit:

As a side note, if I try to use the function version of replaceWith, like so:

$(xml).find('b').replaceWith(function() {
    return '<c>yo</c>' // doesn't matter what I return here
})

I get this error:

TypeError: Cannot call method 'replace' of undefined

Edit 2:

replaceAll works however, but I need to use the function version so I can't settle for this:

$('<c>yo</c>').replaceAll($(xml).find('b')) // works

Edit 3:

This also works:

xml.find('b').replaceWith($('<c>yo</c>')) // but not with the $() around the argument

回答1:


This looks like either a design limitation with replaceWith() or a bug.

When I run:

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

I get a "this[0].innerHTML is undefined" exception. See this jsFiddle.

Drilling into xml, the b node doesn't have an innerHTML member -- which makes a little sense, since it's not HTML. ;)

So, it's looking like replaceWith() may not always play nice with XML. Consider reporting a bug.




回答2:


yes. this is old bug and it still exists. you can workaround it:

$.ajax
  dataType: "xml"
  ...
  success:  (data) ->
    $(data).find("section").each ->
      ugly_but_working_clone = $($(".existing_dom_element").append(this).html())


来源:https://stackoverflow.com/questions/6632482/replacewith-on-xml-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!