jQuery插件创作:为什么有些jQuery.pluginName和其他jQuery.fn.pluginName? [英] jQuery Plugin Authoring: Why do some do jQuery.pluginName and others jQuery.fn.pluginName?

查看:162
本文介绍了jQuery插件创作:为什么有些jQuery.pluginName和其他jQuery.fn.pluginName?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我正在看jCalendar源,创建者有插件的两个不同部分,一个在"jQuery.jcalendar"下,另一个在"jQuery.fn.jcalendar"下.将两者分开的目的是什么?有什么比另一个更重要的呢?

For example, I'm looking at the jCalendar source, and the creator has two different parts of the plugin, one function under "jQuery.jcalendar" and another "jQuery.fn.jcalendar". What is the purpose of having the two separated? What one do over the other?

推荐答案

jQuery.fn.mypluging名称扩展了jQuery对象:

jQuery.fn.mypluging name extends jQuery objects:

$(selector); //a jquery object
$(selector).myplugin();

jQuery.myplugin扩展了jquery对象本身:

jQuery.myplugin extends the jquery object itself:

$; //the jQuery object
$.myPlugin();

通过将插件添加到jQuery.fn中,您可以对该选择器找到的对象进行处理:

By adding your plugin to jQuery.fn you can do stuff to the objects found by that selector:

jQuery.fn.makeRed = function(){
 this.each( function() {
  $(this).css('color', 'red');
 }
}

$('div.someClass').makeRed(); //makes all divs of class someclass have red text

通常为类需要的但不扩展jQuery对象的函数扩展jQuery对象本身.因此,扩展我们之前的示例:

Extending the jQuery object itself is ussually done for functions that your class needs but that do not extend jQuery objects. So to extend our previous example:

jQuery.fn.doStuff = function(){
 this.each( function() {
  $(this).css('color', 'red')
         .append($.doStuff.giveMeRandom());
 }
}

jQuery.doStuff = {
 giveMeRandom: function() {
  return Math.random();
 }
}

$('div.someClass').doStuff(); //makes all divs of class someclass have red text and append a random number to them

这篇关于jQuery插件创作:为什么有些jQuery.pluginName和其他jQuery.fn.pluginName?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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