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

function myfunction(param){
  //some code
}

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

$('#my_div').myfunction()

当前回答

听起来好像你想通过jQuery的原型(也就是写一个jQuery插件)来扩展jQuery对象。这意味着通过调用jQuery函数($(selector/DOM element))创建的每个新对象都有这个方法。

这里有一个非常简单的例子:

$.fn.myFunction = function () {
    alert('it works');
};

Demo

其他回答

听起来好像你想通过jQuery的原型(也就是写一个jQuery插件)来扩展jQuery对象。这意味着通过调用jQuery函数($(selector/DOM element))创建的每个新对象都有这个方法。

这里有一个非常简单的例子:

$.fn.myFunction = function () {
    alert('it works');
};

Demo

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

// 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的元素数量刷新到控制台。

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

用jQuery创建函数最简单的例子是

jQuery.fn.extend({
    exists: function() { return this.length }
});

if($(selector).exists()){/*do something here*/}

要使一个函数在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.fn.extend({
   myfunction: function(param){
       // code here
   },
});
OR
jQuery.extend({
   myfunction: function(param){
       // code here
   },
});
$(element).myfunction(param);