【问题标题】:replaceWith on XML problem关于 XML 问题的 replaceWith
【发布时间】:2011-07-09 03:14:49
【问题描述】:

检查 jQuery 源代码后,我发现我遇到的问题是因为 replaceWith 调用了 XML 文档不存在的 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 代表&lt;a&gt;&lt;c&gt;yo&lt;/c&gt;&lt;/a&gt; 它失败并代表&lt;a&gt;&lt;/a&gt;。我做错什么了吗?我正在使用 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

【问题讨论】:

    标签: javascript jquery xml replacewith


    【解决方案1】:

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

    当我跑步时:

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

    我得到一个"this[0].innerHTML is undefined" 异常。 See this jsFiddle.

    深入xmlb 节点没有 innerHTML 成员——这有点道理,因为它不是 HTML。 ;)

    所以,看起来replaceWith() 可能并不总是与 XML 配合得很好。 Consider reporting a bug.

    【讨论】:

    • 你认为这值得报道吗?
    • @Seth:当然,为什么不呢?可能发生的最坏情况是您会得到“无法修复”,并且至少会记录问题。
    • 是的。它不像人们所期望的那样工作,或者像文档所暗示的那样工作。只需在发布之前搜索以前的错误(我进行了 快速 搜索并没有看到任何内容)。
    • @mu 太短了:不,可能发生的最坏情况是……“你是个令人发笑的白痴;这是证据。” :) 我被称为更糟。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-09-21
      • 2020-06-06
      • 2016-07-20
      • 2016-10-06
      • 1970-01-01
      • 2011-07-23
      • 1970-01-01
      • 2021-04-25
      • 1970-01-01
      相关资源
      最近更新 更多