gpt4 book ai didi

javascript - 我无法将事件绑定(bind)到元素

转载 作者:行者123 更新时间:2023-11-29 16:33:33 25 4
gpt4 key购买 nike

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,监听器似乎并未被绑定(bind)。有什么问题吗?

最佳答案

问题是,当与 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!
<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>');
}

关于javascript - 我无法将事件绑定(bind)到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53441265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com