jQuery ReplaceWith 在替换三个元素时不起作用

发布于 2024-10-16 18:39:28 字数 924 浏览 2 评论 0原文

我试图使用 jQuery 的 ReplaceWith 将单个元素替换为其他三个元素,但它似乎不起作用。

HTML:

<span>first</span>
<span>second</span>
<span>third</span>

JS:

var spans = $("span");
spans.eq(1).replaceWith("<span></span><span></span><span></span>");

如果我写的话,结果应该是:

<span>first</span>
<span></span><span></span><span></span>
<span>third</span>

但是没有任何改变......有什么想法吗?

编辑:这是一个例子,我没有考虑实际 dom 和生成 dom 之间的差异(有区别吗?看起来是这样......)

var spans = $("<span>first</span><span>second</span><span>third</span>");
spans.eq(1).replaceWith($("<span></span><span></span><span></span>"));

所以有一个更准确的描述我的代码。

I'm trying to replace a single element with three other elements, using jQuery's replaceWith, but it doesn't seem to be working.

HTML:

<span>first</span>
<span>second</span>
<span>third</span>

JS:

var spans = $("span");
spans.eq(1).replaceWith("<span></span><span></span><span></span>");

This should if I'm write, result in:

<span>first</span>
<span></span><span></span><span></span>
<span>third</span>

But nothing changes...any thoughts?

EDIT: This was meant as an example, I didn't take into account a difference between actual dom and generated dom (is there a difference? It appears so...)

var spans = $("<span>first</span><span>second</span><span>third</span>");
spans.eq(1).replaceWith($("<span></span><span></span><span></span>"));

So there's a more accurate portrayal of my code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

疧_╮線 2024-10-23 18:39:28

编辑。检查http://jsfiddle.net/z9VDw/3/ 。看来你必须在进行此类操作之前附加断开连接的 DOM 节点。

Edit. Check http://jsfiddle.net/z9VDw/3/ . Seems you have to append disconnected DOM nodes before doing such manipulation.

北渚 2024-10-23 18:39:28

现在我明白你想要做的事情是行不通的。使用片段进行 Dom 操作在 jQuery 中不起作用。 (除了设置属性/css 之外。)replaceWith 在下一个元素之前插入值。在本例中 third 然后再次返回 this,即调用 之前的 this替换为。这是第二个

Now that I see what you're trying to do it won't work. Dom manipulation with fragments doesn't work in jQuery. (Other than setting attributes/css.) replaceWith inserts the value before the next elements. In this case <span>third</span> and then returns this again, which is whatever this was before you called replaceWith. Which was <span>second</span>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文