简体   繁体   English

event.currentTarget在jQuery中总是等于$(this)吗?

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

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? 我喜欢使用$(this)而不是event.currentTarget但在某些情况下可以做得更好吗? 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. 另一个细微差别 - 当检查firebug console.log(this)console.log($(this))给我完全相同的元素。 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') (因为我知道我可以写这个$(this).css('color','white')但是不能写this.css('color','white')

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. 您可以通过使用$.proxy来操作上下文来使其不同,但实际上您可能永远不会。

$(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. 至于另一个问题, this是一个本机DOM元素,而$(this)是一个包装该DOM元素的jQuery对象。 The jQuery wrapper means you can run jQuery functions such as css , which are not available on native DOM elements. jQuery包装器意味着您可以运行诸如css jQuery函数,这些函数在本机DOM元素上不可用。


And, to answer the precise wording of your question, event.currentTarget is normally equal to this , not to $(this) . 而且,为了回答你问题的准确措辞, event.currentTarget通常等于this ,而不是$(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. 没有console.log(this)console.log($j(this))不会给你相同的结果。 $(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 . $(本)转换这一个jQuery对象,因此你可以调用的CSS像它可以在jQuery的对象($(本)),而不是HTML元素,这将是调用的方法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 如果您正在使用jQuery.proxy或其他形式的范围操作,这将等于您提供的任何上下文,而不是event.currentTarget

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM