jQuery Plugin Authoring: Why do some do jQuery.pluginName and others jQuery.fn.pluginName?

后端 未结 1 1666
独厮守ぢ
独厮守ぢ 2020-12-17 02:44

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.jca

相关标签:
1条回答
  • 2020-12-17 03:42

    jQuery.fn.mypluging name extends jQuery objects:

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

    jQuery.myplugin extends the jquery object itself:

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

    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
    

    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
    
    0 讨论(0)
提交回复
热议问题