1

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.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
leto
  • 489
  • 4
  • 18
  • 1
    To see more detail of this issus, please see [JavaScript closure inside loops](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example/750506#750506) – Hikarunomemory Apr 24 '18 at 11:40

1 Answers1

2

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.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101