我正在尝试对 jQuery 对象使用 replaceWith(...) 函数,但它不起作用,当我尝试使用插入的 DOM 元素时它起作用,但在 jQuery 对象中不起作用。
我有这个:
var obj = $('<div id="obj">Text</div>');
obj.replaceWith('<span>New text</span>');
“obj”未替换为新的 HTML。
这是演示: http://jsfiddle.net/v7EA2/
也许我不明白 replaceWith() 函数是如何工作的,
感谢您的帮助。
更新
最佳答案
发生这种情况是因为您的元素没有父元素。将它附加到 DOM 或另一个 jQuery 集合,它将起作用。
我创建了一个 little demo这可能有助于理解此方法的作用。
详情:
我将在这个答案下方的评论中总结详细的研究。感谢 PSL、calberts、Jason P 和 A. Wolff。
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>" );
这意味着 OP 提供的示例应该确实有效。 And it works till version 1.8 .不幸的是,from version 1.9 it stops working .这似乎是一个错误,只有在您尝试替换 jQuery 对象的“根元素”时才会发生。
实际上 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/