我知道有很多关于此的主题,但它们解决了一些可变问题。我的更简单,但它不起作用。只能工作一次。
var bt1;
document.addEventListener('DOMContentLoaded', load);
function load() {
document.body.innerHTML += '<div>welcome</div>';
bt1 = document.getElementById('bt1');
bt1.onclick = clicked;
}
function clicked() {
document.body.innerHTML += '<div>welcome</div>';
}
<body>
<button id="bt1">Click me</button>
</body>
我尝试将 clicked
函数放入和取出 onclick
语句(正如其他一些主题所建议的那样)。
我还尝试移动 bt1
变量声明(并且根本不使用变量)。
最佳答案
每当您分配给容器的 innerHTML
时(即使您只是与现有 HTML 连接),容器的内容都会被删除,并且新的 innerHTML
string 将被浏览器解析并呈现。因此,过去附加到容器内任何内容的监听器将不再起作用。
const container = document.querySelector('#container');
const child = container.children[0];
// Before: the child's parent is the `container`, as expected:
console.log(child.parentElement);
container.innerHTML += '';
// After: the child has no parent element!
// If a listener was attached to the child before,
// the child will no longer even be in the document!
console.log(child.parentElement);
<div id="container">
<div>child</div>
</div>
对于您正在做的事情,可以使用 insertAdjacentHTML
,它不会破坏监听器,但会执行与 innerHTML +=
类似的功能:
var bt1;
document.addEventListener('DOMContentLoaded', load);
function load() {
document.body.innerHTML += '<div>welcome</div>';
bt1 = document.getElementById('bt1');
bt1.onclick = clicked;
}
function clicked() {
document.body.insertAdjacentHTML('beforeend', '<div>welcome</div>');
}
<body>
<button id="bt1">Click me</button>
</body>
或者,显式创建要追加的新元素,并使用 appendChild
:
var bt1;
document.addEventListener('DOMContentLoaded', load);
function load() {
document.body.innerHTML += '<div>welcome</div>';
bt1 = document.getElementById('bt1');
bt1.onclick = clicked;
}
function clicked() {
const div = document.createElement('div');
div.textContent = 'welcome';
document.body.appendChild(div);
}
<body>
<button id="bt1">Click me</button>
</body>
关于JavaScript onclick 函数只工作一次(非常简单的代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53273768/