javascript - 用 jQuery 对象替换

标签 javascript jquery dom dom-manipulation replacewith

我正在尝试对 jQuery 对象使用 replaceWith(...) 函数,但它不起作用,当我尝试使用插入的 DOM 元素时它起作用,但在 jQuery 对象中不起作用。

我有这个:

var obj = $('<div id="obj">Text</div>');
obj.replaceWith('<span>New text</span>');

“obj”未替换为新的 HTML。

这是演示: http://jsfiddle.net/v7EA2/

也许我不明白 replaceWith() 函数是如何工作的,

感谢您的帮助。


更新

请看这里:http://jsfiddle.net/v7EA2/6/

最佳答案

发生这种情况是因为您的元素没有父元素。将它附加到 DOM 或另一个 jQuery 集合,它将起作用。

我创建了一个 little demo这可能有助于理解此方法的作用。

详情:

我将在这个答案下方的评论中总结详细的研究。感谢 PSL、calberts、Jason P 和 A. Wolff。

  1. documentation of replaceWith 陈述如下:

    As of jQuery 1.4, .replaceWith() can also work on disconnected DOM nodes. For example, with the following code, .replaceWith() returns a jQuery set containing only a paragraph.:

    $( "<div/>" ).replaceWith("<p></p>" );

  2. 这意味着 OP 提供的示例应该确实有效。 And it works till version 1.8 .不幸的是,from version 1.9 it stops working .这似乎是一个错误,只有在您尝试替换 jQuery 对象的“根元素”时才会发生。

  3. 实际上 the change in 1.9 was documented :

    Prior to 1.9, .after(), .before(), and .replaceWith() would attempt to add or change nodes in the current jQuery set if the first node in the set was not connected to a document, and in those cases return a new jQuery set rather than the original set. This created several inconsistencies and outright bugs--the method might or might not return a new result depending on its arguments! As of 1.9, these methods always return the original unmodified set and attempting to use .after(), .before(), or .replaceWith() on a node without a parent has no effect--that is, neither the set or the nodes it contains are changed.

    问题是官方文档从未进行过更改。我找到了 a bug发布了关于此的信息,但由于它属于不同的跟踪器而被关闭。


快速解决方案:

在 OP 的情况下,“替换”元素的最简单方法是

var obj = $('<div id="obj">Text</div>');
obj = $('<span>New text</span>');

但前提是它还不在 DOM 中 :).

关于javascript - 用 jQuery 对象替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20616224/

相关文章:

jquery - 使用 jquery 从文本框中清除旧值

javascript - jquery 移动搜索按钮

javascript - 为什么在通过 javascript 添加时 css 转换会回到原来的位置?

用于扩展导航栏的 Javascript 代码无法按预期工作

javascript - 我怎样才能获得在该部分滚动的数量?

javascript - 将 jQuery 加载到 React App 的 Mocha 测试中

javascript - 在 Javascript 中启用/禁用按钮单击处理程序

javascript - 如何将圆添加到 svg 元素

javascript - getElementById 和简单地使用元素的 ID 作为变量有什么区别?

javascript - 是否可以将第 3 方 js 脚本注入(inject)到文档中已有的注释中?