如何创建自定义JQuery函数以及如何使用它? [英] How to create custom JQuery function and how to use it?

查看:68
本文介绍了如何创建自定义JQuery函数以及如何使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找关于这方面的信息 - 如何创建自定义(自己)的JQuery函数以及如何使用它



我在Google中搜索过,但是我没有找到有关这方面的信息。



你能详细解释一下自定义函数吗?

解决方案

通过自定义函数我假设你的意思是插件。如果是这种情况,那么在jQuery网站上有一个很好的教程。基本思想是这样的:

pre $ (function($){
$ .fn.myPlugin = function(){
return this.each(function(){
//做东西
});
};
}(jQuery));

基本上,上面的代码会做一些事情。首先,它捕获 jQuery 的值,并将其传递给一个匿名函数,然后它可以被称为 $ (这是为了让你的插件的用户碰巧使用 $ 标识符作为别的东西仍然可以使用它。)


$ b $然后它在 $。fn 上声明一个方法,它只是 $。prototype 的别名。在该方法内部,这个指的是插件已被调用的匹配元素集合。既然这是一个jQuery对象,并且可能包含多个元素,那么您需要遍历该集合(这就是为什么每个都在那里)。



return 语句用于维护插件与其他jQuery方法的可链接性。由于每个都返回一个jQuery实例,所以插件本身返回一个jQuery实例,而其他jQuery方法显然可以在jQuery实例上调用。


I'm searching for information about that - "How to create custom (own) JQuery function and how to use it"

I've searched in Google, but I didn't found information about that.

Can you explain in details, about custom functions?

解决方案

By "custom function" I am assuming you mean "plugin". If that's the case, there is a good tutorial on the jQuery site. The basic idea is this:

(function($) {
    $.fn.myPlugin = function() {
        return this.each(function() {
            //Do stuff
        });
    };
}(jQuery));

Basically, the code above does a few things. Firstly, it captures the value of jQuery and passes it into an anonymous function where it can then be referred to as $ (this is so that users of your plugin who happen to be using the $ identifier for something else can still use it.)

It then declares a method on $.fn, which is just an alias for $.prototype. Inside that method, this refers to the matched set of elements on which the plugin has been called. Since thats a jQuery object, and may contain multiple elements, you need to iterate over that set (that's why the each is there).

The return statement is used to maintain chainability of the plugin with other jQuery methods. Since each returns an instance of jQuery, the plugin itself returns an instance of jQuery, and other jQuery methods can obviously be called on an instance of jQuery.

这篇关于如何创建自定义JQuery函数以及如何使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆