简体   繁体   English

两次追加 DOM 元素 (jQuery)

[英]Appending a DOM element twice (jQuery)

Can someone explain why the following snippet does not add <foo> to both #a and #b ?有人可以解释为什么以下代码段没有将<foo>添加到#a#b吗?

HTML: HTML:

<div id="a"></div>
<div id="b"></div>

JS: 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.编辑:感谢有用的观点, .append()移动元素这一事实解释了这种行为。 Since the element in my application is actually a Backbone View's .el , I prefer not to clone it.由于我的应用程序中的元素实际上是一个 Backbone View 的.el ,我不想克隆它。

Because using append actually moves the element.因为使用append实际上移动元素。 So your code was moving $foo into the document at #a , then moving it from #a to #b .因此,您的代码将$foo移动到#a处的文档中,然后将其从#a移动到#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:您还可以从$foo附加html ,它只会在其中获取 dom 的副本,而不是元素本身:

$(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.上面的示例假设您有一个更复杂的场景,其中$foo不仅仅是从字符串创建的 jQuery 对象……它更有可能是从 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:如果它实际上只是简单地以这种方式创建并为此目的......根本没有理由创建该 jQuery 对象,您可以简单地附加字符串本身( "<foo>HI</foo>" ) 直接,例如:

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

Try clone .尝试clone This, as the name implies, will copy the $foo element and not move, like append will do.顾名思义,这将复制$foo元素而不是移动,就像append一样。

$(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/这是这两种情况的演示: http : //jsfiddle.net/hungerpain/sCvs7/3/

You need to create a new instance every single time you want to append to the DOM .每次要附加到DOM时,您都需要create a new instance

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.删除要添加的新 div 之前的$符号,因为它计算为 jQuery 对象,并且具有上述限制。 or clone the element.clone元素。

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

Check Fiddle检查小提琴

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.您可以使用 .clone() 方法创建一个新实例以附加到 DOM,因为您当前的代码只是两次引用同一个实例。

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

I tried a trick and it worked.我尝试了一个技巧,它奏效了。 I just nested the function of one button click in another.我只是将一个按钮单击的功能嵌套在另一个中。 i mean I am changing the parent every time to avoid this issue.我的意思是我每次都改变父母以避免这个问题。 the main thing is that when i am writing the click function for button1 click the button2 logic is written under that and the button3 click logic is written inside button2 click method like a hierarchy.主要的是,当我为 button1 单击编写单击函数时,button2 逻辑写在它下面,而 button3 单击逻辑写在 button2 单击方法中,就像层次结构一样。 Just see the code.只看代码。 you will get it.你会得到的。

 <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous" /> <title>Hello, world!</title> </head> <body> <h1>DOM Element Inserting!</h1> <div id="parent"> <div id="result"> <button id="btn1" type="submit" class="btn btn-primary"> Start Cooking </button> </div> </div> <div id="parent2"></div> <div id="parent3"></div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous" ></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous" ></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous" ></script> <script> $(document).ready(function () { $("#btn1").click(function () { $("#lt").remove(); $("#parent2").html(` <button id="btn2" type="button" class="btn btn-success"> Being Prepared </button> `); $("#btn1").remove(); $("#btn2").click(function () { $("#parent3").html(` <button id="btn3" type="button" class="btn btn-info"> Order Ready </button> `); $("#parent2").remove(); $("#btn3").click(function () { alert("Order Completed!!"); }); }); }); }); </script> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM