jQuery - 有没有办法重新使用参数来减少代码重复?
比方说,我有一些像这样的代码:每次我需要它jQuery - 有没有办法重新使用参数来减少代码重复?
jQuery('#retouching-image-1').beforeAfter({
animateIntro: true,
introDelay: 500
});
jQuery('#retouching-image-2').beforeAfter({
animateIntro: true,
introDelay: 500
});
而不是重复animateIntro: true, introDelay: 500
,是有可能把这些值转换成某种形式的可重复使用的变量?
谢谢。
请尝试以下
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
});
jQuery('#retouching-image-1,#retouching-image-2').beforeAfter({
animateIntro: true,
introDelay: 500
});
这是正确的语法。
备选方法:P
仔细查看代码 - 答案就在那里。这些参数实际上只是一个对象(注意围绕它们的花括号)!这意味着你可以做到以下几点:
var animationObj = {animateIntro: true, introDelay: 500};
jQuery('#retouching-image-1').beforeAfter(animationObj);
jQuery('#retouching-image-2').beforeAfter(animationObj);
试试这个:
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
});
或许应该正常工作。
你可以做到这一点在像这样一个循环,
$.each(["#id1", "#id2"], function(_ id){
$(id).beh();
});
你可以这样做:
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
});
我喜欢你的第二个建议的想法,但在我的情况下,事情并不完全正确,代码没有按预期工作。耻辱:( – Matt
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
});
我尝试了你的第二个建议,这似乎是最简单的,但正如下面的其他替代方案之一是不是很正常工作(不是与你的代码,但与它试图运行的功能) - 每个#retouching-image ...的实例必须独立运行该功能,但是使用此代码,事情同时发生,或者根本不发生。 – Matt
大多数人都给出了相同的答案,但是这是第一次。谢谢大家:) – Matt
只是一个说明 - 在我的情况下,第一个选项是好的(将参数添加到变量),但我的jQuery函数需要在每个实例上独立运行,因此是顺序ID而不是可重用类。 – Matt