追加DOM元素两次(jQuery) [英] Appending a DOM element twice (jQuery)
问题描述
有人可以解释为什么以下代码段不会将< foo>
添加到 #a
和 #b
?
Can someone explain why the following snippet does not add <foo>
to both #a
and #b
?
HTML:
<div id="a"></div>
<div id="b"></div>
JS:
$(function(){
var $foo = $("<foo>HI</foo>");
$("#a").append($foo);
$("#b").append($foo);
});
编辑:感谢有用的点,事实上 .append()
移动元素说明这个行为。因为我的应用程序中的元素实际上是一个Backbone View的 .el
,我不喜欢克隆它。
thanks for the helpful points, the fact that .append()
moves the element explains this behavior. Since the element in my application is actually a Backbone View's .el
, I prefer not to clone it.
推荐答案
因为使用 append
实际上会移动元素。因此,您的代码正在 $ foo
移动到 #a
中的文档,然后将其从 #a
至 #b
。你可以克隆它,而不是这样你想要的影响 - 这样它是附加一个克隆而不是初始元素:
Because using append
actually moves the element. So your code was moving $foo
into the document at #a
, then moving it from #a
to #b
. You could clone it instead like this for your desired affect - this way it is appending a clone rather than the initial element:
$(function(){
var $foo = $("<foo>HI</foo>");
$("#a").append($foo.clone());
$("#b").append($foo.clone());
});
您还可以从 html
code> $ foo ,它只会占据其中的dom,而不是元素本身:
You could also append the html
from $foo
, which would just take the dom within it rather than the element itself:
$(function(){
var $foo = $("<foo>HI</foo>");
$("#a").append($foo[0].outerHTML);
$("#b").append($foo[0].outerHTML);
});
这篇关于追加DOM元素两次(jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!