Reputation: 369
I want to change this long piece of code in a single loop: Please help me.
itemAll[0].addEventListener('click', function () {
klik(0)
}, false);
itemAll[1].addEventListener('click', function () {
klik(1)
}, false);
itemAll[2].addEventListener('click', function () {
klik(2)
}, false);
itemAll[3].addEventListener('click', function () {
klik(3)
}, false);
itemAll[4].addEventListener('click', function () {
klik(4)
}, false);
itemAll[5].addEventListener('click', function () {
klik(5)
}, false);
itemAll[6].addEventListener('click', function () {
klik(6)
}, false);
itemAll[7].addEventListener('click', function () {
klik(7)
}, false);
itemAll[8].addEventListener('click', function () {
klik(8)
}, false);
itemAll[9].addEventListener('click', function () {
klik(9)
}, false);
itemAll[10].addEventListener('click', function () {
klik(10)
}, false);
itemAll[11].addEventListener('click', function () {
klik(11)
}, false);
I already tried this but it does not seem to work, I really dont get it why:
for (var i = 0; i < itemAll.length; i++) {
var item = itemAll[i];
item.addEventListener('click', function (item) {
klik(item);
})
}
Anyway thank you for your time, I hope someone can figure this out for me.
Upvotes: 0
Views: 137
Reputation: 3871
It seems like you have an error in your loop. From your code I would assume that you should call your klik()
function on i
instead of item
.
for (var i = 0; i < itemAll.length; i++) {
(function(i) {
itemAll[i].addEventListener('click', function () {
klik(i);
})(i);
}
Upvotes: 3
Reputation: 2403
May I suggest a functional programming example, just to share an alternative solution?
function assign_click_event_to_collection(elements){
assign_click_event_to_element_and_move_to_next(elements, 0);
}
function assign_click_event_to_element_and_move_to_next(elements, index){
if(index > elements.length) return false;
itemAll[index].addEventListener('click', function() {
klik(index);
}, false);
assign_click_event_to_element_and_move_to_next(elements, index+1);
}
assign_click_events_to_collection(itemAll);
Upvotes: 0
Reputation: 289
Try this:
for (var i = 0; i < itemAll.length; i++) {
var item = itemAll[i];
(function(item)
{
item.addEventListener('click', function () {
klik(item);
});
})(item);
}
You need to create a new scope or when you will call klik(item)
item
will always be equal to the last item.
EDIT: It seems you want to pass i
as parameter not item
, replace the item
parameter by i
Upvotes: 3
Reputation: 413712
You can use .forEach()
:
itemAll.forEach(function(item, i) {
item.addEventListener("click", klick.bind(undefined, i));
});
Better yet, you could make sure that all the elements you're working with have a common class, and then just bind a single event handler at the document level that handles clicks and checks for the target element's class. (Basically, the "event delegation" thing that jQuery allows.)
Upvotes: 11