Appending a DOM element twice (jQuery)

拈花ヽ惹草 提交于 2019-12-05 14:48:45

问题


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);
});

jsfiddle

Edit: 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.


回答1:


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());
});

You could also append the html from $foo, which would just take a copy of 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);
});

The above examples are assuming you have a more complicated scenario where $foo isn't just a jQuery object created from a string... more likely it is created from an element in your DOM.

If it is in fact just simply created this way and for this purpose... there is no reason at all to create that jQuery object to begin with, you could simply append the string itself ("<foo>HI</foo>") directly, like:

var foo = "<foo>HI</foo>";
$("#a").append(foo);
//...



回答2:


Try clone. This, as the name implies, will copy the $foo element and not move, like append will do.

$(function(){
    var $foo = $("<foo>HI</foo>");
    $("#a").append($foo.clone());
    $("#b").append($foo.clone());
});

But, why not just use this?

$("#a,#b").append($foo);

This will also work :)

Here's a demo for both these situations : http://jsfiddle.net/hungerpain/sCvs7/3/




回答3:


You need to create a new instance every single time you want to append to the DOM.

Otherwise it refers to the same instance which was already appended.

Remove the $ symbol preceding the new div to be added as that evaluates to a jQuery object and has the limitations as above stated. or clone the element.

$(function(){
    var foo = "<foo>HI</foo>";
    $("#a").append(foo);
    $("#b").append(foo);
});

Check Fiddle




回答4:


You can use the .clone() method to create a new instance to append to the DOM, since your current code just refers to the same instance twice.

$(function(){
    var $foo = $("<foo>HI</foo>");
    var $foo2 = foo.clone();
    $("#a").append($foo);
    $("#b").append($foo2);
});


来源:https://stackoverflow.com/questions/17683549/appending-a-dom-element-twice-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!