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

function myfunction(param){
  //some code
}

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

$('#my_div').myfunction()

当前回答

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

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

稍后调用它:

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

其他回答

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

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

稍后调用它:

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

要使一个函数在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/

来自文档:

(function( $ ){
   $.fn.myfunction = function() {
      alert('hello world');
      return this;
   }; 
})( jQuery );

然后你做了

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

尽管你已经收到了这些答案,但值得注意的是,在函数中使用jQuery并不需要编写插件。当然,如果它是一个简单的一次性函数,我认为写一个插件是多余的。只要将选择器作为参数传递给函数,就可以更容易地完成这个任务。你的代码应该是这样的:

function myFunction($param) {
   $param.hide();  // or whatever you want to do
   ...
}

myFunction($('#my_div'));

注意,变量名$param中的$不是必需的。这只是我的一个习惯,让我很容易记住变量包含一个jQuery选择器。你也可以用参数。

虽然有大量的文档/教程,但你的问题的简单答案是:

// to create a jQuery function, you basically just extend the jQuery prototype
// (using the fn alias)

$.fn.myfunction = function () {
    // blah
};

在该函数中,this变量对应于调用函数的jQuery包装集。比如:

$.fn.myfunction = function () {
    console.log(this.length);
};

$('.foo').myfunction();

... 将类foo的元素数量刷新到控制台。

当然,语义方面还有更多的东西(以及最佳实践等),所以一定要仔细阅读。