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