简体   繁体   English

为什么以下代码生成4个元素而不是2个?

[英]Why does the following code generate 4 elements instead of 2?

I'm trying to understand, why does the following code generate FOUR new paragraphs instead of just TWO. 我试图理解,为什么以下代码生成四个新段落而不是两个。

Could anyone explain what exactly happens in the $("p").before($("p").clone()); 任何人都可以解释$("p").before($("p").clone());到底发生了什么$("p").before($("p").clone()); part? 部分?

 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").before($("p").clone()); }); }); </script> </head> <body> <p>paragraph 1.</p> <p>paragraph 2.</p> <button>Clone all p elements, and append them to the body element</button> </body> </html> 

Clone copies each of <p> and returns two paragraph elements which are inserted by before. 克隆将复制每个<p>并返回两个段落元素,这些元素之前插入。

A more meaningful explanation: 更有意义的解释是:

  • You have got two <p> elements in your HTML. HTML中有两个<p>元素。

  • $("p").clone() clones BOTH elements and passes them to before() $("p").clone()克隆两个元素并将它们传递给before()

  • before() is executed TWICE, one time for each paragraph 两次执行before() ,每个段落一次

As output, you get 2*2 = 4 new paragraphs. 作为输出,您将获得2 * 2 = 4个新段落。

$("p").clone() alone results $(“ p”)。clone()单独结果

在此处输入图片说明

then $("p").before($("p").clone()) means it will append the result of $("p").clone() before both paragraph tags. 然后$(“ p”)。before($(“ p”)。clone())表示它将$(“ p”)。clone()的结果附加在两个段落标签之前。

在此处输入图片说明

When you clone() , it creates a deep copy of the p elements. 当您clone() ,它将创建p元素的深层副本。

before() will append the copies not only to the existing elements, but also to the cloned elements. before()将副本附加到现有元素,而且还附加到克隆的元素。

Use a more specific class name to append them, not $("p"), especially when the cloned elements and elements you are inserting before is the same type of element. 使用更具体的类名来附加它们,而不是$(“ p”),尤其是当克隆的元素和之前要插入的元素是同一类型的元素时。

At least use different element like this. 至少使用这样的不同元素。

$("p").clone().appendTo('body');

 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").clone().appendTo('.clone-target'); }); }); </script> </head> <body> <p>paragraph 1.</p> <p>paragraph 2.</p> <div class="clone-target"></div> <button>Clone all p elements, and append them to the body element</button> </body> </html> 

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

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