我无法将事件绑定到元素

时间:2018-11-23 05:52:23

标签: javascript

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,但似乎听众并没有受到束缚。有什么问题吗?

2 个答案:

答案 0 :(得分:5)

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

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 +=不同,会在容器中重新创建所有元素:< / p>

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>');
}

答案 1 :(得分:0)

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];
 document.body.appendChild(a[i]);
 document.body.innerHTML += "<br>"
 console.log(a[0].innerHTML);
 }
for (let i = 0; i < color.length; i++) {
   var el = document.getElementById("b" + (i + 1)) ;
   console.log(el)
el.addEventListener('click', function() {
   alert('color');
  })
}

https://jsfiddle.net/3zw0a1tx/