I would like each click is associated with the right occurrence in the table boxes.
var J = jQuery.noConflict();
const bNumber = 2;
var boxes = new Array(bNumber);
boxes[0] = new Array("#cch", "#cc");
boxes[1] = new Array("#sinh", "#sin");
for(var k=0;k<bNumber;k++) {
J( boxes[k][0] ).click( function() {
//J( boxes[k][1] ).toggle();
});
}
With this solution, each click is associated with boxes[2][1]
JavaScript has no block scope, only function scope. That is why creating functions in a loop is tricky. Every closure has a reference to the same variable (
kin your case). After the last iteration of the loop,khas the value2.To capture the current value of the loop counter you have to introduce a new scope, i.e. call a function. E.g. with an immediate function:
Another way is to create a function that generates the click handler:
OT:
You should not use
new Arrayto initialize arrays. There is no need to define the size of the array beforehand. Using array literal notation is more concise: