如何让新克隆的按钮与现有的事件监听器一起工作?

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

在按下“离开”按钮时,我希望在屏幕上显示 10 个新的“离开”按钮。单击这些按钮中的每一个都需要在屏幕上显示 10 个新按钮。

但是只有原来的“离开”按钮显示了 10 个新按钮,新克隆的没有。

JavaScript代码:

const container = document.querySelector('.container');
const leaveButton = document.querySelector('#leave');

leaveButton.addEventListener('click', () => {
    for (let i = 0; i < 10; i++) {
        const newButton = document.createElement('button');
        newButton.innerHTML = leaveButton.innerHTML;
        newButton.style.top = Math.random() * window.innerHeight + 'px';
        newButton.style.left = Math.random() * window.innerWidth + 'px';
        newButton.setAttribute("id", "leave");
        container.appendChild(newButton);
    }
});

HTML代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>PressTheButton</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <button id="leave">Leave</button>
        <h1>It's simple</h1>
        <p>Just click the buttons</p>
    </div>
    <script src="script.js"></script>
</body>
</html>
javascript html button
1个回答
1
投票

您应该使用委托事件侦听,而不是将事件侦听器添加到固定按钮。在下面的代码片段中,我将 click 事件添加到父 container。在事件侦听器回调函数中,我简单地检查一下,点击元素的 .textContent 是否等于“离开”,如果不是,我立即返回而不执行任何操作。

const container = document.querySelector('.container');
const leaveButton = document.querySelector('#leave');

container.addEventListener('click', ev => {
if (ev.target.textContent!=="Leave") return;
for (let i = 0; i < 10; i++) {
    const newButton = document.createElement('button');
    newButton.innerHTML = leaveButton.innerHTML;
    newButton.style.top = Math.random() * window.innerHeight + 'px';
    newButton.style.left = Math.random() * window.innerWidth + 'px';
    newButton.setAttribute("id", "leave");
    container.appendChild(newButton);
}
});
button {position:absolute}
<head>
<meta charset="UTF-8">
<title>PressTheButton</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
    <button id="leave">Leave</button>
    <h1>It's simple</h1>
    <p>Just click the buttons</p>
</div>

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