替换XML问题 [英] replaceWith on XML problem

查看:74
本文介绍了替换XML问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在检查了jQuery源代码之后,我发现我遇到的问题是因为 replaceWith 调用 html 不存在XML文档。是 replaceWith 不应该在XML文档上工作吗?

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.

我对jQuery了解不多,但不应该这样吗?

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>')

而不是 xml 代表< a>< c> yo< / c>< / a> 它失败并代表< a取代;< / A> 。我做错什么了吗?我正在使用jQuery 1.6.2。

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.

编辑:

作为一方请注意,如果我尝试使用 replaceWith 的功能版本,如下所示:

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

我收到此错误:

TypeError: Cannot call method 'replace' of undefined

编辑2:

replaceAll 然而,但是我需要使用函数版本所以我不能满足于此:

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

编辑3:

这也有效:

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


推荐答案

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

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

当我跑步时:

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

我得到this [0]。 innerHTML未定义异常。 查看此jsFiddle

钻入 xml b 节点没有innerHTML成员 - 这有点意义,因为它不是HTML。 ;)

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

因此,它看起来像 replaceWith()可能并不总是与XML很好。 考虑报告错误

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

这篇关于替换XML问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆