如何克隆元素并在每次单击按钮时创建它

问题描述 投票:0回答:2

我想复制 div 元素并在单击按钮时将其粘贴到其旁边。

我想复制带有 id="box" 的元素,并在每次单击按钮时将其粘贴到其旁边。

<!DOCTYPE html>
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
</head>
<body>

<div style="width: 18rem;" class="card" id="box">
    <div class="card-body">
        <h5 class="card-title" id="Cat1"></h5>
        <p class="card-text">No Products Created</p>
        <a href="#" class="btn btn-primary">+</a>
    </div>
</div>

<button onclick="addItem()">Click Me!</button>
  
<script>
    function addItem() {
          //code goes here
    }
</script>
 
</body>
</html>
javascript html
2个回答
6
投票

您可以使用

cloneNode()
方法克隆元素,然后使用
appendChild()
方法将克隆的元素放置在任何位置。

document.addEventListener("DOMContentLoaded", function () {
    const container = document.getElementById("container");
    const cloneButton = document.getElementById("clone-button");

    function cloneElement() {
        const elementToClone = document.querySelector(".clone-me");
        const clonedElement = elementToClone.cloneNode(true);
        container.appendChild(clonedElement);
    }
    cloneButton.addEventListener("click", cloneElement);
});
<div id="container">
    <div class="clone-me">
        <p>This is the element to clone.</p>
    </div>

</div>

<button id="clone-button">Clone Element</button>

请注意,

cloneNode()
方法可能会导致重复的ID。你应该处理这个问题,引用来自 MDN 的内容:

警告:
cloneNode()
可能会导致文档中出现重复的元素 ID!

如果原始节点具有

id
属性,并且克隆将被放置在同一个文档中,那么您应该将克隆的 ID 修改为唯一。

此外,

name
属性可能需要修改,具体取决于是否需要重复名称。


4
投票

这是解决方案。

cloneNode()
方法可以用来复制元素,并且不能使用id,因为id是唯一的并且可以在页面中使用一次。您可以使用类进行复制。

function addItem() {   

  const node = document.querySelector(".card-body");
  const clone = node.cloneNode(true);

  document.getElementById("box").appendChild(clone);
}
<!DOCTYPE html>
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
</head>
<body>

<div style="width: 18rem;" class="card" id="box">
    <div class="card-body">
        <h5 class="card-title" id="Cat1"></h5>
        <p class="card-text">No Products Created</p>
        <a href="#" class="btn btn-primary">+</a>
    </div>
</div>

<button onclick="addItem()">Click Me!</button>
  
</body>
</html>

© www.soinside.com 2019 - 2024. All rights reserved.