2015-10-28 35 views
3

我使用这行代码颇有几分:将多种功能下1个主要功能

.hide().insertBefore("#placeholder").fadeIn(1000);

有没有办法让这个函数和变量(非常肯定不能用var,但想我会问),所以我可以根据需要调用它?我知道我可以复制/粘贴,但它混乱了代码,看到一遍又一遍。

我想:

function properDisplay() { 
    .hide().insertBefore("#placeholder").fadeIn(1000); 
} 

但是,这并不工作。

回答

4

你可以把它一个插件:

$.fn.properDisplay = function(){ 
    return this.hide().insertBefore("#placeholder").fadeIn(1000); 
}; 

用法:

$('#SomeElement').properDisplay(); 
+0

感谢@Guffa。这工作正常。它也帮助我在我的发言中找到另一个错误。非常感谢! – megler

4

您需要的元素对象传递的参数

function properDisplay(ele) { 
 
    $(ele).hide().insertBefore("#placeholder").fadeIn(1000); 
 
}

0
function properDisplay(param) { 
    $(param).hide().insertBefore("#placeholder").fadeIn(1000); 
} 

,然后只是简单地调用它像这样:

properDisplay(this); 
0

你也可以把它到一个jQuery插件:

$.fn.properDisplay = function(whereToInsert, delay) { 
    if (delay === undefined) delay = 1000; 
    return this.hide().insertBefore(whereToInsert).fadeIn(delay); 
}); 

然后:

$(".something").properDisplay("#placeholder"); 

在一个插件,this是一个jQuery对象,而不是一个DOM元素的引用。插件返回jQuery对象是很常见的,这样就可以像通常的做法那样链接函数了。