Example explains the difference between this and $of this in JQuery

  • 2020-03-30 04:31:17
  • OfStack

This is rarely used in jquery. When I looked at the code, I found it was used, so I debugged the value of this, thinking that's why. It's useful. Here is a summary of the difference and use of this and $(this).

What does $(this) generate?

What does $() generate? In fact, $()=jquery(), which means that a jquery object is returned.

Usually we use $() directly for simplicity. In fact, the function omits a parameter context. The matching object, $(selector, context), is selected from the selector and returned as a jQuery wrapper set.

The context can be a collection of Dom objects or a jQuery wrapper set, passed in to indicate that a matching object is to be selected from the context, and not passed in to indicate that the scope is a document object (that is, all the objects of the page), that is, $(selector)=$(selector,document).

This is the HTML object that calls the function.

Example:


$("#textbox").hover(  
  function() {  
       this.title = "Test";  
  },  
  fucntion() {  
      this.title = "OK " ;  
  }  
);

This is actually an Html element (textbox), this is in js. Textbox has a text property, so there's nothing wrong with that.


$("#textbox").hover(  
       function() {  
   $(this).title = "Test";  
       },  
       function() {  
   $(this).title = "OK";  
       } 
);

The $(this) here is a JQuery object, and the JQuery object has a title property, so this is an error.

Conclusion:

This indicates that the current context object is an HTML object that can call the properties and methods owned by the HTML object.
$(this), the context object that represents a jquery context object, can call jquery methods and property values.

Example (TAB) :


tabs($("#nav a"), $(".content")); 
function tabs(tab, content){
 content.hide();
 content.eq(0).show();
 tab.click(function(){
  var index = tab.index(this);
  tab.removeClass("current");
  $(this).addClass("current");
  content.hide();
  content.eq(index).animate({opacity:'show'}, 200);
 });
}


Related articles: