JavaScript onclick function only works once (very

2019-08-28 08:12发布

问题:

I know there are many topics about this, but they address some variable issue. Mine is much more simple, but it is not working. Only works once.

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>

I tried taking the clicked function in and out of the onclick statement (as some other topics suggested).

I also tried moving the bt1 variable declaration around (and not using a variable at all).

回答1:

Whenever you assign to the innerHTML of a container (even if you're just concatenating with existing HTML), the container's contents will be removed, and the new innerHTML string will be parsed and then rendered by the browser. So, listeners that used to be attached to anything inside of the container will no longer work.

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>

For what you're doing, either use insertAdjacentHTML, which will not corrupt listeners, but will perform similar functionality to 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>

Or, explicitly create the new element to append, and use 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>



回答2:

Another quick fix would be to reattach the listener in clicked mehtod.

var bt1;
document.addEventListener('DOMContentLoaded', load);

function load() {
  document.body.innerHTML += '<div>welcome</div>';
  bt1 = document.getElementById('bt1');
  bt1.onclick = clicked;
}

function clicked(a) {
  document.body.innerHTML += '<div>welcome</div>';
  bt1 = document.getElementById('bt1');
  bt1.onclick = clicked;
}
<body>
  <button id="bt1">Click Me</button>
</body>