I am trying to create many droppable elements inside a loop. Here is the code:
我想在循环中创建许多可放置的元素。这是代码:
for (var i = 0; i < 10; i++) {
for(var j = 0; j < 20; j++){
$("#main").append( '<a "href="javascript:void(0);" id="click'+i+'-'+j+'" onclick="change_to_blocked('+i+','+j+')"><img id="image'+i+'-'+j+'" src="http://localhost/free.png" />');
$("#main").append('');
tmp1 = i;
tmp2 = j;
$('#image'+i+'-'+j).droppable({
drop: function(e,ui) {
$('#image'+(i)+'-'+(j)).attr('src','/bot.png');
console.log(i);
}
});
}
$("#main").append('<br>'); }
However, it only applies to the last value of the loop.
但是,它仅适用于循环的最后一个值。
1 个解决方案
#1
You need to create a closure
otherwise at the time the events occur the values of i
and j
will be the values of the last iteration of the loop.
您需要创建一个闭包,否则在事件发生时,i和j的值将是循环的最后一次迭代的值。
One way is to wrap the code within loop in an IIFE - Immediately Invoked Function Expression
一种方法是将代码包含在IIFE中的循环中 - 立即调用函数表达式
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 20; j++) {
(function (i, j) {
$("#main").append('<a "href="javascript:void(0);" onclick="return showIndexes('+i +','+j+')">Item # '+i+'-'+j+'</a><br>');
})(i, j); //params used in the IIFE
}
}
By passing the values as arguments of the function they are closed in the function and won't be changed by subsequent iterations
通过将值作为函数的参数传递,它们在函数中被关闭,并且不会被后续迭代更改
Some of the html rendering was left out for clarity
为清楚起见,遗漏了一些html渲染
When looping over arrays with jQuery, you can create a closure by using $.each
which will provide you the index as first argument of the callback
使用jQuery循环遍历数组时,可以使用$ .each创建一个闭包,它将为索引提供回调作为回调的第一个参数
#1
You need to create a closure
otherwise at the time the events occur the values of i
and j
will be the values of the last iteration of the loop.
您需要创建一个闭包,否则在事件发生时,i和j的值将是循环的最后一次迭代的值。
One way is to wrap the code within loop in an IIFE - Immediately Invoked Function Expression
一种方法是将代码包含在IIFE中的循环中 - 立即调用函数表达式
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 20; j++) {
(function (i, j) {
$("#main").append('<a "href="javascript:void(0);" onclick="return showIndexes('+i +','+j+')">Item # '+i+'-'+j+'</a><br>');
})(i, j); //params used in the IIFE
}
}
By passing the values as arguments of the function they are closed in the function and won't be changed by subsequent iterations
通过将值作为函数的参数传递,它们在函数中被关闭,并且不会被后续迭代更改
Some of the html rendering was left out for clarity
为清楚起见,遗漏了一些html渲染
When looping over arrays with jQuery, you can create a closure by using $.each
which will provide you the index as first argument of the callback
使用jQuery循环遍历数组时,可以使用$ .each创建一个闭包,它将为索引提供回调作为回调的第一个参数