我正在构建一个小部件,该小部件在数组中的每个jQuery DOM元素上调用一个特定的插件。
MyApp.forms是一个对象数组。每个Object都有一个jQuery包装的DOM元素。
我正在做以下事情:
$(MyApp.forms).each(function(i){
var individualForm = this;
/*
individualForm is an Object {
prop: 'value,
$el: somejQueryElement,
...
}
*/
individualForm.$el.thePlugin({
// options
})
.on('pluginEvent', function() {
individualForm; // refers to the last object in MyApp.forms
this; // refers to the last
$(this); // same problem
}).on('pluginEvent2', function() {
// same problem as above here.
});
});
事件pluginEvent
和pluginEvent2
被附加到所有individualForm
的$el
。但当他们开火时,我总是得到最后一个元素
我觉得这是一个常见的JavaScript闭包问题。
我尝试使用for
循环并在其中创建IIFE
,但它不起作用,因为函数在事件触发时执行。尽管这两个事件都在所有元素上触发,但我只执行了附加到最后一个元素的处理程序。
更新:
找到修复程序。但不知道为什么以及如何运作。每一个individualForm.$el
元素都是具有class="some-class"
的input
元素。
在代码的其他地方,另一个开发人员正在使用旧版本的jQuery执行$('.some-class').bind(...
。然后再次使用更新版本的jQuery(使用noConflict
$
)。页面上有2个jQuery
。修复方法是删除第一个.bind
。
你能尝试一下吗:
$(MyApp.forms).each(function(i){
var form = this;
(function(individualForm) {
individualForm.$el.on('something', function() {
individualForm; // refers to the last object in MyApp.forms
this; // refers to the last
$(this); // same problem
}).on('somethingElse', function() {
// same problem as above here.
});
})(form);
});
您应该将personalForm封装在闭包中。否则,作用域将发生更改,并指向数组的最后一个元素。