I would like each click is associated with the right occurrence in the table boxes
.
开发者_JAVA百科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 (k
in your case). After the last iteration of the loop, k
has the value 2
.
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:
for(var k=0;k<bNumber;k++) {
(function(index) {
J( boxes[index][0] ).click( function() {
J( boxes[index][1] ).toggle();
});
}(k));
}
Another way is to create a function that generates the click handler:
function getClickHandler(element) {
return function() {element.toggle()});
}
for(var k=0;k<bNumber;k++) {
J(boxes[k][0] ).click(getClickHandler(J(boxes[k][1])));
}
OT:
You should not use new Array
to initialize arrays. There is no need to define the size of the array beforehand. Using array literal notation is more concise:
var boxes = [["#cch", "#cc"], ["#sinh", "#sin"]];
Try this:
var J = jQuery.noConflict();
const bNumber = 2;
var boxes = new Array(bNumber);
boxes[0] = new Array("#cch", "#cc");
boxes[1] = new Array("#sinh", "#sin");
function toggleHandler(k) {
J( boxes[k][1] ).toggle();
}
for(var k=0;k<bNumber;k++) {
J( boxes[k][0] ).click( function() {
toggleHandler(k);
});
}
For readable and understandable code, store the target box on the element as 'data'?
for(var k=0;k<bNumber;k++) {
J(boxes[k][0]).data("box") = $(boxes[k][1]);
J(boxes[k][0]).click( function() {
J(this).data("box").toggle();
});
}
精彩评论