首页 > 解决方案 > 我无法将事件绑定到元素

问题描述

const color = ['red', 'orange', 'yellow', 'green', 'blue', 'navy', 'purple'];
let a = [];
for (let i = 0; i < color.length; i++) {
  a[i] = document.createElement("input");
  a[i].type = 'button';
  a[i].id = 'b' + (i + 1);
  a[i].value = color[i];
  a[i].addEventListener('click', function() {
    alert('color');
  })
  document.body.appendChild(a[i]);
  document.body.innerHTML += "<br>"
  console.log(a[0].innerHTML);
}

尽管addEventListener. 问题是什么?

标签: javascript

解决方案


问题是,当与innerHTML容器的 (例如,与 your document.body.innerHTML += "<br>")连接时,容器将被清空,然后用新的 HTML 字符串重新解析。如果您之前将侦听器附加到容器中的元素,则该侦听器将不在 HTML 字符串中,因此它不会转移到相同位置的元素。

const div1 = document.querySelector('#somediv');
document.body.innerHTML += '';
const div2 = document.querySelector('#somediv');

console.log(div1 === div2);
// False, the container's contents were re-parsed, the new div is different!
<div id="somediv"></div>

br使用与您用于的相同appendChild方法附加您的a[i]

const color = ['red', 'orange', 'yellow', 'green', 'blue', 'navy', 'purple'];
let a = [];
for (let i = 0; i < color.length; i++) {
  a[i] = document.createElement("input");
  a[i].type = 'button';
  a[i].id = 'b' + (i + 1);
  a[i].value = color[i];
  a[i].addEventListener('click', function() {
    alert('color');
  })
  document.body.appendChild(a[i]);
  document.body.appendChild(document.createElement('br'));
}

或者insertAdjacentHTML改为使用,它的作用类似于.innerHTML +=,但不同.innerHTML +=的是,它不会重新创建容器中的所有元素:

const color = ['red', 'orange', 'yellow', 'green', 'blue', 'navy', 'purple'];
let a = [];
for (let i = 0; i < color.length; i++) {
  a[i] = document.createElement("input");
  a[i].type = 'button';
  a[i].id = 'b' + (i + 1);
  a[i].value = color[i];
  a[i].addEventListener('click', function() {
    alert('color');
  })
  document.body.appendChild(a[i]);
  document.body.insertAdjacentHTML('beforeend', '<br>');
}


推荐阅读