jQuery插件创作:为什么有些人做jQuery.pluginName和其他jQuery.fn.pluginName?

前端之家收集整理的这篇文章主要介绍了jQuery插件创作:为什么有些人做jQuery.pluginName和其他jQuery.fn.pluginName?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
例如,我正在查看jCalendar源代码,创建者有两个不同的插件部分,一个函数在“jQuery.jcalendar”下,另一个函数在“jQuery.fn.jcalendar”下.两者分开的目的是什么?一个人做了什么呢?

解决方法

jQuery.fn.mypluging名称扩展了jQuery对象:
  1. $(selector); //a jquery object
  2. $(selector).myplugin();

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

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

通过将您的插件添加到jQuery.fn,您可以对该选择器找到的对象执行操作:

  1. jQuery.fn.makeRed = function(){
  2. this.each( function() {
  3. $(this).css('color','red');
  4. }
  5. }
  6.  
  7. $('div.someClass').makeRed(); //makes all divs of class someclass have red text

扩展jQuery对象本身是为了您的类需要但不扩展jQuery对象的函数.所以扩展我们前面的例子:

  1. jQuery.fn.doStuff = function(){
  2. this.each( function() {
  3. $(this).css('color','red')
  4. .append($.doStuff.giveMeRandom());
  5. }
  6. }
  7.  
  8. jQuery.doStuff = {
  9. giveMeRandom: function() {
  10. return Math.random();
  11. }
  12. }
  13.  
  14. $('div.someClass').doStuff(); //makes all divs of class someclass have red text and append a random number to them

猜你在找的jQuery相关文章