Hello I\'m a newcomer in JavaScript and JQuery language. I started to see some examples of JQuery script.
i have the following code segment:
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.
$('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 clicked this
is a global variable that refers to the calling DOM object, which I believe is window
by 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:
this
is 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 wantMost 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.