给一个有1个变量/对象的函数给定几个参数

give several parameters to a function with 1 variable/object

本文关键字:函数 几个 参数 变量 一个 1个 对象      更新时间:2023-09-26

以jQuery animate函数为例:正常情况下是这样工作的:

$("#div1").animate({
                width: '300px',
            }, 1000, function() {
                console.log("animate 1 done");
            });

我想要这样的:

animateConfig = [{
                width: '300px',
            }, 1000, function() {
                console.log("animate1 done");
            }];
startAnimate($("#div1"), animateConfig);
function startAnimate(obj, animateConfig) {
    console.log(animateConfig);
    obj.animate(animateConfig);
}

也是小提琴:http://fiddle.jshell.net/hVXKM/1/

尝试:

obj.animate.apply(obj, animateConfig);

.animate()方法允许您将对象作为第二个参数传递。这样你就可以做到:

文档:.animate(属性,选项)

animateConfig = {
    props: { width: '300px' },
    options: {
        duration: 1000,
        complete: function() {
           console.log("animate1 done");
        }
    }
}

所以你可以这样做:

function startAnimate(obj, config) {
    obj.animate(config.props, config.options);
}
startAnimate(obj, animateConfig);