jQuery - 有没有办法重用参数来减少代码重复?

时间:2011-09-23 15:45:12

标签: jquery variables parameters reusability

假设我有一些像这样的代码:

jQuery('#retouching-image-1').beforeAfter({
    animateIntro: true,
    introDelay: 500
});
jQuery('#retouching-image-2').beforeAfter({
    animateIntro: true,
    introDelay: 500
});

不是每次需要时都复制animateIntro: true, introDelay: 500,是否可以将这些值放入某种可重复使用的变量中?

感谢。

7 个答案:

答案 0 :(得分:3)

尝试以下

var x = {
    animateIntro: true,
    introDelay: 500
};

jQuery('#retouching-image-1').beforeAfter(x);
jQuery('#retouching-image-2').beforeAfter(x);

另一个可能更易于使用的选项是使用类而不是id来标记这些元素。假设您为每个这些项添加了`retouchImage'类。然后,您可以将代码简化为以下

jQuery('.retouchImage').beforeAfter({
    animateIntro: true,
    introDelay: 500
});

答案 1 :(得分:2)

function dostuff(element) {
    element.beforeAfter({
        animateIntro: true,
        introDelay: 500
    });
}

jQuery(function() {
  dostuff(jQuery('#retouching-image-1,#retouching-image-2')); 
});

创建一个函数,或者只是改为:

jQuery('#retouching-image-1,#retouching-image-2').beforeAfter({
    animateIntro: true,
    introDelay: 500
});

虽然就个人而言,我会创建一个类并以这种方式执行:

jQuery('.retouching-images').beforeAfter({
    animateIntro: true,
    introDelay: 500
});

答案 2 :(得分:1)

仔细查看代码 - 答案就在那里。那些参数实际上只是一个对象(注意它们周围的花括号)!这意味着您可以执行以下操作:

var animationObj = {animateIntro: true, introDelay: 500};

jQuery('#retouching-image-1').beforeAfter(animationObj);
jQuery('#retouching-image-2').beforeAfter(animationObj);

答案 3 :(得分:1)

试试这个:

options = {
    animateIntro: true,
    introDelay: 500
}

jQuery('#retouching-image-1').beforeAfter(options);
jQuery('#retouching-image-2').beforeAfter(options);

更好:

jQuery('#retouching-image-1, #retouching-image-2').beforeAfter({
    animateIntro: true,
    introDelay: 500
});

应该也可以。

答案 4 :(得分:1)

你可以像这样循环,

$.each(["#id1", "#id2"], function(_ id){
     $(id).beh();
});

答案 5 :(得分:1)

你可以这样做:

jQuery('#retouching-image-1, #retouching-image-2').beforeAfter({
    animateIntro: true,
    introDelay: 500
});

或者如果您有更多ID,则可以使用attribute starts with selector

jQuery('img[id^=retouching-image-]').beforeAfter({
    animateIntro: true,
    introDelay: 500
});

答案 6 :(得分:0)

jQuery('#retouching-image-1,#retouching-image-2').beforeAfter({
    animateIntro: true,
    introDelay: 500
});

这是正确的语法。 替代方式:P