开发者

replaceWith on XML problem

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 att开发者_如何学Goributes 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


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.


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())
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜