2011-09-23 106 views
3

比方說,我有一些像這樣的代碼:每次我需要它jQuery - 有沒有辦法重新使用參數來減少代碼重複?

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

而不是重複animateIntro: true, introDelay: 500,是有可能把這些值轉換成某種形式的可重複使用的變量?

謝謝。

回答

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 
}); 
+0

大多數人都給出了相同的答案,但是這是第一次。謝謝大家:) – Matt

+0

只是一個說明 - 在我的情況下,第一個選項是好的(將參數添加到變量),但我的jQuery函數需要在每個實例上獨立運行,因此是順序ID而不是可重用類。 – Matt

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

這是正確的語法。 備選方法:P

1

仔細查看代碼 - 答案就在那裏。這些參數實際上只是一個對象(注意圍繞它們的花括號)!這意味着你可以做到以下幾點:

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

jQuery('#retouching-image-1').beforeAfter(animationObj); 
jQuery('#retouching-image-2').beforeAfter(animationObj); 
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 
}); 

或許應該正常工作。

0

你可以做到這一點在像這樣一個循環,

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

你可以這樣做:

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

,或者如果你有多個標識,您可以使用attribute starts with selector

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

我喜歡你的第二個建議的想法,但在我的情況下,事情並不完全正確,代碼沒有按預期工作。恥辱:( – Matt

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 
}); 
+0

我嘗試了你的第二個建議,這似乎是最簡單的,但正如下面的其他替代方案之一是不是很正常工作(不是與你的代碼,但與它試圖運行的功能) - 每個#retouching-image ...的實例必須獨立運行該功能,但是使用此代碼,事情同時發生,或者根本不發生。 – Matt