gpt4 book ai didi

jQuery 如何用不同的元素替换根节点

转载 作者:行者123 更新时间:2023-12-01 07:55:16 24 4
gpt4 key购买 nike

我尝试用不同的元素替换组的根节点,但 replaceWith 似乎不起作用。

div = $('<div></div>'); 
div.replaceWith('<span></span>'); // returns [<span></span>]
console.log(div); // [<div></div>]

div = $('<div><span></span></div>');
div.replaceWith('<a></a>'); // returns [<div><span></span></div>]
console.log(div); // [<div><span></span></div>]

div 不会被替换,并且返回值始终是其本身,而不是被替换的节点(div)。这似乎与返回被替换元素的正常(有记录的)实现相反。

div = $('<div><span></span></div>');
div.find('span').replaceWith('<a></a>'); // returns [<span></span>]
console.log(div); // [<div><a></a></div>]

如果 replaceWith 不起作用,如何用另一个元素替换根节点?

最佳答案

一种可能的方法是首先创建一个替换元素,然后将原始元素的内容附加到其中。像这样:

var orig = $('<div>dasdasd<span>dasdas</span>dasdeasd</div>');
var repl = $('<span></span>');
repl.append(orig.contents());
<小时/>

至于您所描述的 replaceWith 行为,这实际上是故意的。引用 docs :

Prior to jQuery 1.9, .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. The method might or might not have returned a new result depending on the number or connectedness of its arguments!

As of jQuery 1.9, .after(), .before(), and .replaceWith() always return the original unmodified set. Attempting to use these methods on a node without a parent has no effect — that is, neither the set nor the nodes it contains are changed.

<小时/>

关于jQuery 如何用不同的元素替换根节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25144621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com