可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
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);
Here's a demo:
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); }
回答2:
You stored the value in the id
attribute, so just use it:
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 () {alert(this.getAttribute('id'));}); document.body.appendChild(categoryButton); }
In the event handler, this
references the <input>
element itself, so you can just retrieve the attribute value.
回答3:
Thats because you are assigning that eventlistener to an object that is not still in the DOM (thats because you created this element after the DOM was loaded)
Try this:
categoryButton.onclick = function(col){ alert(col); }
You can either declare a function to a var and then reasign this function to the event handler:
var myFunction = function(){ alert("I'm a function"); } myElement.onclick = myFunction;