Javascript 如何创建一个 jQuery 函数(一个新的 jQuery 方法或插件)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12093192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:05:45  来源:igfitidea点击:

How to create a jQuery function (a new jQuery method or plugin)?

javascriptjqueryfunction

提问by multimediaxp

I know that in JavaScript the syntax is as follows:

我知道在 JavaScript 中的语法如下:

function myfunction(param){
  //some code
}

Is there a way to declare a function in jQuery that can be added to an element? For example:

有没有办法在 jQuery 中声明一个可以添加到元素的函数?例如:

$('#my_div').myfunction()

回答by Candide

From the Docs:

文档

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

Then you do

然后你做

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

回答by Pevara

In spite of all the answers you already received, it is worth noting that you do not need to write a plugin to use jQuery in a function. Certainly if it's a simple, one-time function, I believe writing a plugin is overkill. It could be done much more easily by just passing the selector to the function as a parameter. Your code would look something like this:

尽管您已经收到了所有答案,但值得注意的是,您无需编写插件即可在函数中使用 jQuery。当然,如果它是一个简单的一次性函数,我相信编写一个插件是多余的。只需将选择器作为参数传递给函数,就可以更轻松地完成此操作。您的代码如下所示:

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

myFunction($('#my_div'));

Note that the $in the variable name $paramis not required. It is just a habit of mine to make it easy to remember that that variable contains a jQuery selector. You could just use paramas well.

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

回答by Richard Neil Ilagan

While there is a plethoraof documentation / tutorials out there, the simple answer for your question is this:

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

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

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

Inside that function, the thisvariable corresponds to the jQuery wrapped set you called your function on. So something like:

在该函数内部,该this变量对应于您调用函数的 jQuery 包装集。所以像:

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

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

... will flush to the console the number of elements with the class foo.

... 将带有 class 的元素数量刷新到控制台foo

Of course, there is a bit more to semantics than that (as well as best practices, and all that jazz), so make sure you read up on it.

当然,语义远不止于此(以及最佳实践和所有爵士乐),因此请务必仔细阅读。

回答by Richard Dalton

To make a function available on jQuery objects you add it to the jQuery prototype (fn is a shortcut for prototype in jQuery) like this:

要使函数在 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
    }
}

This is usually called a jQuery plugin.

这通常称为jQuery 插件

Example - http://jsfiddle.net/VwPrm/

示例 - http://jsfiddle.net/VwPrm/

回答by user1619962

$(function () {
    //declare function 
    $.fn.myfunction = function () {
        return true;
    };
});

$(document).ready(function () {
    //call function
    $("#my_div").myfunction();
});

回答by Paul D. Waite

Yup — what you're describing is a jQuery plugin.

是的 - 你所描述的是一个 jQuery 插件。

To write a jQuery plugin, you create a function in JavaScript, and assign it to a property on the object jQuery.fn.

要编写 jQuery 插件,您需要在 JavaScript 中创建一个函数,并将其分配给 object 上的一个属性jQuery.fn

E.g.

例如

jQuery.fn.myfunction = function(param) {
    // Some code
}

Within your plugin function, the thiskeyword is set to the jQuery object on which your plugin was invoked. So, when you do:

在您的插件函数中,this关键字设置为调用您的插件的 jQuery 对象。所以,当你这样做时:

$('#my_div').myfunction()

Then thisinside myfunctionwill be set to the jQuery object returned by $('#my_div').

然后thisinsidemyfunction将被设置为$('#my_div').

See http://docs.jquery.com/Plugins/Authoringfor the full story.

有关完整故事,请参阅http://docs.jquery.com/Plugins/Authoring

回答by Novasol

You can also use extend(the way you create jQuery plugins):

您还可以使用扩展(创建 jQuery 插件的方式):

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

    myfunction2: function () 
    {
    }
});

Usage:

用法:

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

回答by Michael

You can write your own jQuery plugins(function which can be called on selected elements) like below:

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

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


Call it later like:


稍后调用它,例如:

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

回答by Jamiec

Yes, methods you apply to elements selected using jquery, are called jquery plugins and there is a good amount of info on authoringwithin the jquery docs.

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

Its worth noting that jquery isjust javascript, so there is nothing special about a "jquery method".

它值得指出的是jQuery的刚刚的javascript,所以有关于“jQuery的方法,”没有什么特别的。

回答by Jamiec

You can always do this:

你总是可以这样做:

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