Better understand "this" in JQuery plugin


when your write a JQuery plugin , you will use 'this', Below code will help you have a better understand on this.

Detail code is on http://jsfiddle.net/sunchonggui/wZkMa/

$.fn.greenify = function() {

    /** Here this refers to the JQuery object on which the plugin is applied,  It's got a prototype with all jQuery methods that can be inherited by your element (like css). As it is already a jQuery object, there's no need to double wrap it in $(). However, $(this) will also work but is not required. */
    
    this.each(function(index, element){
       /** Here this is the same as element, it is a plain javascript dom object.  */
        console.log(this);
        console.log(element);
        /** Below line will cause error, because this means a plain javascript dom object hence it doesn't have css method. */
        //this.css("color","red"); 
        /** Below line will work well , since you have wrapped a jquery object. */
        $(this).css("color","red");
    });
    //this.css( "color", "green" );
  //  console.log(this);// you will see a jQuery object in the console
};


$( "li" ).greenify();


html :


     
  • 1

  •  
  • 2

  •  
  • 3





     
  • 1

  •  
  • 2

  •  
  • 3





你可能感兴趣的:(jquery)