javascript - 在 Javascript 中,有没有一种方法可以复制 HTML 包装器,而不会使其 "Event Listeners"失去其功能?

标签 javascript html dom duplicates clonenode

因此,在我的 Javascript 中,我只能复制一次 HTMl Id="characters"包装器。我知道它在技术上应该是一个“类”而不是“Id”,因为它将是一个重复的“Id”,但由于某种原因我不明白;当我将“getElementById”更改为“getElementsByClassName”并将 HTML“Id”更改为“类”时,它根本不重复。另外,因为我使用的是clone.Node(true),所以我失去了重复包装器中“addEventListeners”的功能。有没有办法只使用普通 Javascript 来纠正这个问题?好像这还不够烦人,我的重复包装器似乎正在从我的 CSS 网格中抛出。这一切都非常乏味和麻烦,所以我感谢您提供的任何建议。

这是我当前的 HTML。

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="css/style.css">
        <h1><!--D&D DM Tool--><h1>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title></title>
    </head>
    <body>
        <div id="header-container">
            <h1 id="header">Game Tools</h1>
        </div>

        <div class="importantbuttons">
            <button id="resetbutton">Next Round</button>
            <button id="orderbutton">Order</button>
            <button id="zerobutton">Zero</button>
            <button id="deadremoverbtn">Bring Out the Dead!</button>
            <button id="addnpcbtn">Add NPC</button>
        </div>

        <div id="grid"> 
            <div class="characters">
                <div id="subgrid" class="subgrid" >
                    <div class="name-bloodiedstuff">
                        <div class="halfWayDown"></div>
                        <div class="character-name-display">Name</div>
                        <button class="name-submit-btn">Submit</button>
                        <input type="text" class="input-name-el" placeholder="Name">
                        <div class=int-stuf>
                            <div class="roll-display">Iniative</div>
                            <button class="iniativebtn">Submit</button>
                            <input type="number" class="iniative-roll-el" placeholder="Iniative Roll">
                        </div>
                        <div class="healthpoints-display">Healthpoints</div>
                        <button class="hp-submit-btn">Submit</button>
                        <input type="number" class="input-hp-el" placeholder="Total HealthPoints">
                        <button class="hp-deductin-btn">Submit</button>
                        <input type="number" class="input-hp-deduction-el" placeholder="Damage">
                    </div>
                    <div class="weapons-display">Weapons</div>
                    <button class="weapon-btn">Submit</button>
                    <input type="text" class="weapon-input-el" placeholder="Weapons">
                    <button class="active-btn" class="button">Active</button>       
                </div>
            </div>
        </div>
    </body>
    <script src="mainCopy.js"></script>
</html>

这是我当前的 Javascript 复制函数。

addNpcBtn.addEventListener("click",function(){
    var characterSubGrids=document.getElementsByClassName("characters");
    console.log(characterSubGrids[0]);
    var characterSubGridsClone=characterSubGrids[0].cloneNode(true);
    let grid=document.getElementById("grid");
    console.log(grid);
    grid.appendChild(characterSubGridsClone);
});

最佳答案

From the MDN article on cloneNode

Cloning a node copies all of its attributes and their values, including intrinsic (inline) listeners. It does not copy event listeners added using addEventListener() or those assigned to element properties (e.g., node.onclick = someFunction).

看起来像cloneNode可能已经忽略了您试图忽略的事件监听器。

如果您尝试克隆 <div>以某种方式保留其 <button> 上的事件监听器 children ,我不认为 DOM 有这样的方法。相反,您必须将相同的事件监听器附加到新克隆的按钮。类似于以下内容:

// Fetch the container and save that element as a constant for future use
const container = document.querySelector('#container')
// Create the addHandlers function for future use
function addHandlers (span) {
  // Find the first button child of the element provided as first parameter
  const button = span.querySelector('button')
  // Add a click event listener to that button
  button.addEventListener('click', () => {
    // On click, clone the parent element (the span, not the button)
    const clone = span.cloneNode(true)
    // Find the first input child of this new clone
    const input = clone.querySelector('input')
    // Set its value to the empty string (by default, the clone would conserve the value of the original)
    input.value = ''
    // Add handlers to the clone which were lost during cloning
    addHandlers(clone)
    // Add the clone into the DOM as a new, last child of the container
    container.appendChild(clone)
  }, false)
}
// Find all elements with class name 'duplicatable' and run the `addHandlers` function on each element
document.querySelectorAll('.duplicatable').forEach(addHandlers)
<div id="container">
  <h2>Characters</h2>
  <span class="duplicatable">
    <button>Add a new character</button>
    <input type='text' placeholder='name' />
  </span>
</div>

关于javascript - 在 Javascript 中,有没有一种方法可以复制 HTML 包装器,而不会使其 "Event Listeners"失去其功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71398889/

相关文章:

javascript - 在您选择其中任何一个之前,将显示带有空白的 HTML 选择框

javascript - 在 Angular 2 中访问 DOM 属性

javascript - 使用 React-Redux 为 Provider 提供有效的 DOM 嵌套

Javascript - 拆分动态字符串获取括号内的值

c# - 自定义下拉列表样式(CSS/JS 与 ASP.NET C# 连接)

html - 固定位置div,显示在下一个div之上

javascript - 抓取最近的前一个 div 的内容

javascript - cookie 的 Rails 编码与 JavaScript decodeURIComponent 不兼容

javascript - 当您在方法上使用编辑器时,TinyMCE 更新工具栏(初始化后)

javascript - 如何创建富文本编辑器