addEvenListener在动态按钮上不起作用-javascript [英] addEvenListener doesn't work on dynamic button - javascript
问题描述
所以我目前正忙于学习JavaScript。我创建了一些动态按钮,并尝试向其添加addEvenListener。但这是行不通的,我无法弄清楚为什么行不通。我只是在测试一些东西,然后尝试使用本地存储中的值创建按钮。几乎可以正常工作,只有addEvenListener无法正常工作。我只想使用本地存储中的密钥发出简单警报。
So I'm currently busy with learning JavaScript. I created some dynamic buttons and I tried to add an addEvenListener to it. But it doesn't work and I can't figure it out why it doesn't work. I'm just testing some stuff and I try to create buttons with values from the localstorage. It is almost working, only the addEvenListener isn't working. I just want a simple alert with the key from the localstorage.
for (var i = 0; i <= localStorage.length-1; i++) {
var categoryButton = document.createElement('input');
categoryButton.setAttribute('class', 'forumMenu');
categoryButton.setAttribute('type', 'button');
categoryButton.setAttribute('name', localStorage.key(i));
categoryButton.setAttribute('value', localStorage.key(i));
categoryButton.setAttribute('id', localStorage.key(i));
categoryButton.addEventListener('click', function(col){
alert(col);
}(localStorage.key(i)),true);
forumMenu.appendChild(categoryButton);
}
有人知道为什么它不起作用吗?
Does anyone know why it doesn't work?
推荐答案
您没有将函数传递给 EventTarget。 addEventListener()
。您将立即执行并传递以下结果:
You're not passing a function to EventTarget.addEventListener()
. You're immediately executing and passing the result of this:
function (col) {
console.log(col);
}(localStorage.key(i))
...这是 未定义
一个>。您可以使用以下语法对此进行修改:
... which is undefined
. You can ammend that by using the following syntax:
categoryButton.addEventListener('click', (function(col) {
// return a function to addEventListener
return function(){
console.log(col);
}
})(localStorage.key(i)),true);
这是一个演示:
var input;
for (var i = 0; i <= 5; i++) {
input = document.createElement('input');
input.type = "button"
input.value = i;
input.addEventListener('click', function(i) {
// return a function to addEventListener
return function() {
console.log(i);
}
}(i), true);
document.body.appendChild(input);
}
这篇关于addEvenListener在动态按钮上不起作用-javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!