最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is event.currentTarget always equal to $(this) in jQuery? - Stack Overflow

programmeradmin5浏览0评论

Is this phrase always true?

$("p").click(function(event) {
  alert( event.currentTarget === this ); 
});  

Is one method preferred over the other? I like to use $(this) instead of event.currentTarget but can one do better in some conditions? Which is better? Are absolutely the same?

And another nuance - When checking on firebug console.log(this) and console.log($(this)) gives me exactly the same element. If they are the same - what is different? (since I know I can write this $(this).css('color','white') but can't write this.css('color','white')

Is this phrase always true?

$("p").click(function(event) {
  alert( event.currentTarget === this ); 
});  

Is one method preferred over the other? I like to use $(this) instead of event.currentTarget but can one do better in some conditions? Which is better? Are absolutely the same?

And another nuance - When checking on firebug console.log(this) and console.log($(this)) gives me exactly the same element. If they are the same - what is different? (since I know I can write this $(this).css('color','white') but can't write this.css('color','white')

Share Improve this question edited Feb 2, 2016 at 7:25 rink.attendant.6 46.2k64 gold badges110 silver badges157 bronze badges asked Dec 22, 2011 at 12:40 AlonAlon 7,75820 gold badges63 silver badges100 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 13

Generally, yes, it will be the same. You can make it different by using $.proxy to manipulate the context, but in practice you probably never will.

$(document.body).on('click', $.proxy(function(e) {
    console.log(this);            // window
    console.log(e.currentTarget); // document.body
}, window));

As to the other question, this is a native DOM element, whereas $(this) is a jQuery object wrapping that DOM element. The jQuery wrapper means you can run jQuery functions such as css, which are not available on native DOM elements.


And, to answer the precise wording of your question, event.currentTarget is normally equal to this, not to $(this).

Part of your answer is above. I hope its clear enough.

No console.log(this) and console.log($j(this)) will not give you the same result. $(this) converts this to a jQuery Object and hence you can call .css like methods which can be called on jQuery objects($(this)) and not the HTML elements which will be this.

This property will typically be equal to the this of the function.

If you are using jQuery.proxy or another form of scope manipulation, this will be equal to whatever context you have provided, not event.currentTarget

发布评论

评论列表(0)

  1. 暂无评论