jQuery ReplaceWith 在替换三个元素时不起作用
我试图使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编辑。检查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.
现在我明白你想要做的事情是行不通的。使用片段进行 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 returnsthis
again, which is whateverthis
was before you calledreplaceWith
. Which was<span>second</span>