gpt4 book ai didi

javascript - forEach 方法不起作用

转载 作者:行者123 更新时间:2023-12-04 03:24:18 25 4
gpt4 key购买 nike

HTML:

<input type="button" value="Start" id="start">

JavaScript:

var inp = document.querySelectorAll('.z1');

Array.prototype.forEach.call(inp, function(item, i, arr) {
item[i].addEventListener('click', function() {
alert('fsdfs');
}, false);
});

document.getElementById('start').addEventListener('click',function() {
var gg = '<input type="button" value="Button1" class="z1"><input type="button" value="Button2" class="z1">';
document.body.insertAdjacentHTML('beforeEnd', gg);
});

这个想法是,当您点击插入正文中的 INPUT 时,应该触发警报。

最佳答案

Alert 不会为新元素触发,因为您从未将事件绑定(bind)到它们。而是将点击事件委托(delegate)给主体,它最终会在主体中冒泡:

document.body.addEventListener('click', function(e) {
if (e.target.className == 'z1') {
alert('fsdfs');
}
}, false);

document.getElementById('start').addEventListener('click',function() {
var gg = '<input type="button" value="Button1" class="z1"><input type="button" value="Button2" class="z1">';
document.body.insertAdjacentHTML('beforeEnd', gg);
});
<input type="button" value="Start" id="start">

请记住,在委托(delegate)事件的情况下,您需要检查事件是否发生在正确的元素上。就像在演示中一样,您可以检查事件目标类名称。

关于javascript - forEach 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27743713/

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