Reputation: 599
I have a couple of questions.
Why doesn't the following work?
var xps = ['+', '-', '*', '/'];
for (var i = 0; i < $('.operator').length; i++) {
$('.operator:eq(' + i + ')').click(function () {
operatorGeneric(xps[i]);
})
}
where .operator
is a class given to my operators and operatorGeneric
is a function that handles my operators. When I log xps[i] it gives me undefined, and when I put '+', for example, as the parameter of operatorGeneric it works fine.
My second question is, is there a better way of doing this? I'm trying to avoid writing out a separate function for each element.
Upvotes: 1
Views: 26
Reputation: 67525
You need to use closures to attach an event inside loop :
var xps = ['+', '-', '*', '/'];
for (var i = 0; i < $('.operator').length; i++) {
(function (i) {
$('.operator:eq(' + i + ')').click(function () {
operatorGeneric(xps[i]);
});
})(i);
}
Or use a function like :
var xps = ['+', '-', '*', '/'];
for (var i = 0; i < $('.operator').length; i++) {
attachEvent(i);
}
function attachEvent(i){
$('.operator:eq(' + i + ')').click(function () {
operatorGeneric(xps[i]);
});
}
Or simply replace var i
with let i
as @Hikarunomemory suggest.
Upvotes: 2