what is the meaning of the word “this” in Jquery script

前端 未结 3 538
余生分开走
余生分开走 2021-01-29 07:51

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:

 

        
相关标签:
3条回答
  • 2021-01-29 08:14

    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.

    0 讨论(0)
  • 2021-01-29 08:21
    • $('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 want
    0 讨论(0)
  • 2021-01-29 08:29

    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.

    0 讨论(0)
提交回复
热议问题