$(document).ready(function(){
$("button").click(function(){
$("p").clone().appendTo("body");
});
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Clone all p elements, and append them to the body element</button>
</body>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").clone().appendTo("body");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Clone all p elements, and append them to the body element</button>
</body>
</html>
此代码产生段的克隆,但克隆的数量成倍增长等上第一点击创建第二次点击1个拷贝创建2个克隆如何修复它,以便每次创建一个副本,以及如何为每个动态创建的新元素指定新的ID。
第一次你的身体只有2个p标签。你克隆并附加到身体。现在你的身体有4个p标签。如果你通过身体搜索,你会得到所有4个p标签。如果你现在克隆,克隆4个标签。在你追加之后,现在你在身体中留下了8个标签。问题是,你想在点击事件中考虑所有的身体标签还是只考虑特定的2 p标签? – Sidtharthan
嗨@Ahtisham Shahid,如果任何答案解决了您的问题,您应该接受它。这将有助于其他具有相同问题的用户找到修补程序 –