在jQuery队列中调用自己的方法

时间:2013-03-07 18:20:50

标签: jquery methods call undefined

我在jQuery中创建了自己的方法:

$.fn.plop = function(){
    // Method 
};

我试图将它称为如下队列:

$(elems[0]).plop().delay(800).fadeOut();

但Firefox返回错误:

  

TypeError:$(...)。plop(...)未定义

对导致问题的原因有什么看法?感谢。

2 个答案:

答案 0 :(得分:1)

如果您希望它是可链接的,则需要在函数中返回jQuery。如果没有别的话,只需return $;

示例:

$.fn.plop = function(){
    // Method
    return this.html('bar'); // html() returns jQuery
};

$('#myDiv').plop().delay(800).fadeOut();

http://jsfiddle.net/mUuhF/

答案 1 :(得分:0)

要正确扩展jQuery,您需要编写如下所示的方法:

$.fn.plop = function () {  
    return this.each(function () {

        // Do something for each element

    });
};

这将允许您对任何jQuery元素集合运行.plop(),将行为或操作应用于每个元素,它将返回原始集合,以便您可以继续将其他方法调用链接到它。 / p>