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);
}Run Code Online (Sandbox Code Playgroud)
尽管如此,听众似乎并没有受到约束addEventListener.问题是什么?
问题是,当与innerHTML容器(例如,与您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!Run Code Online (Sandbox Code Playgroud)
<div id="somediv"></div>Run Code Online (Sandbox Code Playgroud)
使用您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'));
}Run Code Online (Sandbox Code Playgroud)
或者使用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>');
}Run Code Online (Sandbox Code Playgroud)