So I have this eventListner that calls an Class, works like a charm but only once since inte call the add class with index 0.
Im trying to create a loop that will call every add class inside the script, but i cant get loop...
This is the event listner without the loop
var AddEvent = "add";
var addClass = document.getElementsByClassName(AddEvent)[0]
addClass.addEventListener("click", addDiceEvent, false);
function addDiceEvent() {
dicesides_funcfunc();
}
And this is what Im trying to create.
function AddDice(){
for (i = 0; i < 5; i++) {
var addClass = document.getElementsByClassName("add");
addClass.addEventListener("click", addDiceEvent, false);
function addDiceEvent(){
dicesides_funcfunc();
}
}
} AddDice();
Any ideas ?
Hope this work.......
var addClassArr= document.getElementsByClassName(AddEvent);
for (var x in addClassArr)
{
var addClass = addClassArr[x];
addClass.addEventListener("click", addDiceEvent, false);
}
function addDiceEvent() {
dicesides_funcfunc();
}
You need to create new skope in for loop, try this:
function AddDice(){
for (i = 0; i < 5; i++) {
(function(){
var addClass = document.getElementsByClassName("add");
addClass.addEventListener("click", function(){
dicesides_funcfunc();
}, false);
})();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.