Is event.currentTarget always equal to $(this) in jQuery?

前端 未结 3 815
失恋的感觉
失恋的感觉 2021-02-13 19:29

Is this phrase always true?

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

Is one method preferred over the o

相关标签:
3条回答
  • 2021-02-13 19:42

    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).

    0 讨论(0)
  • 2021-02-13 19:55

    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 讨论(0)
  • 2021-02-13 20:07

    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.

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