我知道在JavaScript中语法是这样的:

function myfunction(param){
  //some code
}

是否有一种方法可以在jQuery中声明一个可以添加到元素中的函数?例如:

$('#my_div').myfunction()

当前回答

是的,你应用于使用jquery选择的元素的方法,被称为jquery插件,在jquery文档中有大量关于创作的信息。

值得注意的是,jquery只是javascript,所以“jquery方法”并没有什么特别之处。

其他回答

你可以这样做:

jQuery.fn.extend({
   myfunction: function(param){
       // code here
   },
});
OR
jQuery.extend({
   myfunction: function(param){
       // code here
   },
});
$(element).myfunction(param);

要使一个函数在jQuery对象上可用,你需要将它添加到jQuery原型中(fn是jQuery原型的快捷方式),如下所示:

jQuery.fn.myFunction = function() {
    // Usually iterate over the items and return for chainability
    // 'this' is the elements returns by the selector
    return this.each(function() { 
         // do something to each item matching the selector
    }
}

这通常被称为jQuery插件。

例如—http://jsfiddle.net/VwPrm/

是的,你应用于使用jquery选择的元素的方法,被称为jquery插件,在jquery文档中有大量关于创作的信息。

值得注意的是,jquery只是javascript,所以“jquery方法”并没有什么特别之处。

你可以编写自己的jQuery插件(可以在选定的元素上调用的函数),如下所示:

(function( $ ){
    $.fn.myFunc = function(param1, param2){
        //this - jquery object holds your selected elements
    }
})( jQuery );

稍后调用它:

$('div').myFunc(1, null);

你也可以使用extend(创建jQuery插件的方式):

$.fn.extend(
{
    myfunction: function () 
    {
    },

    myfunction2: function () 
    {
    }
});

用法:

$('#my_div').myfunction();