html - javascript addEventListener in for loops uses last variable for event -
here's code
<body> <div id = "elementbox"> </div> <script> var container = document.getelementbyid("elementbox"); function item_select() { alert("e"); var selected_element = document.getelementsbyclassname("on"); selected_element.classname = "off"; alert(selected_element); } (var = 0; < 20; i++) { dive = document.createelement("div"); dive.id = i+1; dive.classname = "off"; if (dive.id === 8) { dive.classname = "on"} dive.innerhtml = "<p>e</p>; (function(i) { dive.addeventlistener("click", function(i) { document.getelementbyid(i).classname = "on"; item_select(); }, true) })(i); container.appendchild(dive);
}
</script> </body> </html>
as can see addeventlistener uses incremented variable (i) change classname of specific div, when event called equal 20. how can avoid ?
no, don't believe going on. have immediate-invocation close value of i
.
i think problem i
event
object:
(function(i) { dive.addeventlistener("click", function(i) { ^-- should not here document.getelementbyid(i).classname = "on"; item_select(); }, true) })(i);
it seems click handler sets class on
next <div>
. consider using dive.nextsibling
. avoids need use id
, i
. it's possible more complex behaviour required maybe having id
useful.
Comments
Post a Comment