0

我需要做这样的事情:

for (var i in arrayOfObjects) {
    var options = arrayOfObjects[i];
    $('.' + options.className).hide('middle', function(){
        //And here I need to use a data from options. 
        //How can I pass 'options' object here? 
        $(options.attribute).doSomethig();
    });
}
4

1 回答 1

1

这是因为您options在异步回调方法中使用了闭包变量。一种解决方案是在循环内创建一个私有闭包,如下所示

for (var i in arrayOfObjects) {
    (function(options){
        $('.' + options.className).hide('middle', function () {
            //And here I need to use a data from options. 
            //How can I pass 'options' object here? 
            $(options.attribute).doSomethig();
        });
    })(arrayOfObjects[i])
}

另一种解决方案是使用 jQuery 进行迭代

$.each(arrayOfObjects, function(i, options){
    $('.' + options.className).hide('middle', function () {
        //And here I need to use a data from options. 
        //How can I pass 'options' object here? 
        $(options.attribute).doSomethig();
    });
})
于 2013-09-12T10:48:27.270 回答