我目前正在开发一个基于 gridster 的 CMS 模块,需要让最终用户创建不同的布局,多次实例化 gridster。
当我循环遍历应该设置的网格数量并尝试定义回调时,我的问题出现了,这些回调应该根据定义它们的迭代使用不同的参数来调用:当我测试它们时,它们似乎继承了(最后一个)相同的值。
我认为这是一个结束问题,我正在尝试解决这个问题,甚至阅读了这个论坛上的几篇帖子,但没有成功,如果有人能给我一个提示,让我走上正确的道路,我将非常感激。
这是我的代码:
var gridster= [];
var id_layouts = [];
$(".selectedLayout").each(function(){
id_layouts.push($(this).val());
});
for(i=0; i<id_layouts.length; i++){
makeGridster(i, id_layouts[i]);
}
function makeGridster(index, id_layout){
gridster[index] = $('#blockcompositeGrid'+id_layout+' > ul').gridster({
widget_margins: [10, 10],
widget_base_dimensions: [100, 100],
draggable:{
stop: function(){
return function(i, l){
updateSerialization(i, l)
}(index, id_layout)
}
}
}).data('gridster');
}
function updateSerialization(index, id_layout){
console.log(index, id_layout);
}
网格已建成,没关系。 正如您所看到的,我正在尝试调用一个函数作为拖动操作停止的回调,并且应该使用不同的参数来调用该函数。 我找到了this这似乎与我需要的类似,但不幸的是我对coffescript一无所知,并且从'do'的coffescript文档( coffescript.org )我看不出我做错了什么。 预先感谢您的帮助
最佳答案
尝试在循环和停止函数的定义中使用除 i 之外的不同变量名称。由于范围的限制,他们可能会互相踩踏。另外,在循环中使用 var 定义 i,引用不带 var 的变量/属性使其成为全局变量。
What is the purpose of the var keyword and when to use it (or omit it)?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for
关于javascript - 在带有闭包的循环中创建 gridster 的多个实例,以使用不同的参数调用相同的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20934012/