循环将动态参数传递给回调函数 [英] Pass dynamic parameters to callback function in a loop

查看:79
本文介绍了循环将动态参数传递给回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想动态设置一些jQuery动画.

I wanted to set some jQuery animatios dynamically.

代码:

function anim(data) {
    for (index in data) {
        (function(){
            var props = {};
            props[data[index].property] = data[index].value;
            data[index].elem.animate(
                props,
                500,
                function() {
                    data[index].callback();
                }
            );
        })();
    }
}

var data =[
    {
        elem: elem1,
        property: 'prop1',
        value: 'val1',
        callback: function() {
            console.log('callback1');
        }
    },
    {
        elem: elem2,
        property: 'prop2',
        value: 'val2',
        callback: function() {
            console.log('callback2');
        }
    },
];
anim(data);

问题在于绑定回调.触发回调后,data[index]在当前作用域中不可用.有人可以告诉我如何设置这些回调属性吗?

The problem is binding callbacks. When the callback is fired, data[index] is not available in current scope. Can somebody tell me how to set those callback propery?

推荐答案

在这里,您使用的closure

Here you used a closure of Immediately-invoked function expression. You have to pass data[index] as parameter.

(function(dindex){
        var props = {};
        props[dindex.property] = dindex.value;
        dindex.elem.animate(
            props,
            500,
            function() {
                dindex.callback();
            }
        );
 })(data[index]);

这篇关于循环将动态参数传递给回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆