What Is The Meaning Of The Word "this" In Jquery Script
Solution 1:
It refers to each of p tags in your selector $("p") that gets clicked. For example, you can see html of each p tag you clicked on like this:
$("p").click(function(){
alert($(this).html());
});
Notice also that $(this) and this in above context mean different things. The latter this refers to DOM element itself which won't have jQuery methods/properties available to it, for example:
$("p").click(function(){
alert(this.html());
});
Won't work because html() won't be available because this refers to DOM element in there. So if you want to use jQuery methods, use $(this) instead.
Solution 2:
Most time in such snippets of jQuery this refers to HTMLElement object. Here this is the HTMLParagraphElement or P tag object.
$(this) refers to the jQuery object created from current HTMLElement object.
But keep in mind in JavaScript the meaning this changes depending on where the function is called.
Solution 3:
$('p')will add one or more paragraph elements (wrapped in jQuery magic) to an array.click()is a jQuery function that will be called on each of the paragraph elements found (in the array)function(){...}is the definition of that click event, where you can perform any javascript option when the paragraph is clickedthisis a global variable that refers to the calling DOM object, which I believe iswindowby default, but in this instance it would be each paragraph HTML element.
Because you want to call a jQuery function (hide()) on the paragraph element, you have to wrap the base (HTML/DOM) object with all the jQuery functions, which is what $(this) does; it takes this and adds all the jQuery stuff to it, to turn it into a jQuery object, so that you can call all the jQuery functions. In other words:
thisis the base object$(this)is almost the same, but its a jQuery object, which inherits the object in scope, so that you can call all the jQuery sugar you want
Post a Comment for "What Is The Meaning Of The Word "this" In Jquery Script"