开发者

jQuery '$(this)'

开发者 https://www.devze.com 2023-03-03 16:09 出处:网络
Why 开发者_开发知识库and when would you use $(this) instead of this?You use this when you are in the scope of a DOM object (or any other object for that matter)

Why 开发者_开发知识库and when would you use $(this) instead of this?


You use this when you are in the scope of a DOM object (or any other object for that matter)

For example:

$('a').click(function(){
     var href = $(this).prop('href'); //refers to to this a tags href
     var href1 = this.href; //ALSO refers to to this a tags href
})


When you want to use jQuery functions on the DOM element referenced by this.

See the jQuery documentation:

The second and third formulations of this function create a jQuery object using one or more DOM elements that were already selected in some other way. A common use of this facility is to call jQuery methods on an element that has been passed to a callback function through the keyword this (...)


In some languages like JavaScript, "this" represents an object reference to enclosing one.

For example, if you've a JavaScript prototype called Person, and some method "B" of Person uses "this" in its body, "this" is current Person instance.

Applying that to jQuery, $() shortcut function accepts different types of input parameters: for example a CSS selector, a document object reference and so on. One of accepted input parameters is an instance of DOM element.

That's if you're handling "click" event for some element, you can do that:

$("#someIdOfSomeElement").click(function() {
      // "this" is the element with "someIdOfSomeElement" identifier
      $(this).append("hello world!");
    }
);

Giving "this" to $() shortcut function returns a jQuery object managing the DOM element with jQuery's properties and methods.


Alex gives a really good response to this here


the $() way shows the browser that this is a jquery varible. $(this) means the current element.


$(this) is the jQuery $() function applied to the this javascript keyword. You should use it when you want to get the current this (a DOM element) as a jQuery object.


Every time this means an instance of HTMLElement and you wish to wrap it by jQuery to have it's magic available. <p onclick="$(this).text('Clicked!');">Sun is shining.</p>

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号