开发者

jQuery - is there a way to re-use parameters to cut down on code duplication?

Let's say I have some code like this:

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

Rat开发者_如何学运维her than duplicating animateIntro: true, introDelay: 500 each time I need it, is it possible to put these values into some kind of re-useable variable?

Thanks.


Try the following

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

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

Another, probably more re-usable option is to use a class instead of an id to tag these elements. Say you added the `retouchImage' class to every one of these items. Then you could simplify your code to the following

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


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

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

Create a function, or simply do this instead:

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

Although personally, I would create a class and do it this way:

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


Look closer at the code -- the answer is in there. Those parameters are actually just an object (note the curly braces surrounding them)! That means you could do the following:

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

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


Try this:

options = {
    animateIntro: true,
    introDelay: 500
}

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

Even better:

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

should probably work as well.


You can do it in a loop like so,

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


You could do:

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

or if you have more ids you could use the attribute starts with selector

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


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

That's the correct syntax. Alternative way :P

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜