jquery中的event.currenttarget 和 this有什么区别?

在网上看一些资料,event.currenttargetthis说的很相似,它们具体有什么区别?

阅读 5.8k
3 个回答

一般来说,thisevent.currentTarget 是一致的。

但是,如果使用了某种作用域替换,(比如 jquery.Proxy,或者 ES6、CoffeeScript 等里用了 =>),this 可能有别的含义了,用 event.currentTarget 就更安全。

一般人们更容易混淆的是 event.targetevent.currentTarget

摘自 jQuery event.currentTarget 文档 的原话

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

就是说一般情况下,currentTargetthis 是一样的。

但是,要写这样的代码就不一样了

$("#theButton").on("click", function(e) {
    alert( event.currentTarget === this ); // false
}.bind(window));

event.currentTarget指向事件所绑定的元素,而event.target始终指向事件发生的元素。

HTML代码:

<div id="wrapper"> 
    <a href="#" id="inner">click here!</a> 
</div>

javascript代码:

<script type="text/javascript" src="source/jquery.js"></script> 
<script> 
    $('#wrapper').click(function(e) { 
        console.log('#wrapper'); 
        console.log(e.currentTarget); 
        console.log(e.target); 
    }); 
    $('#inner').click(function(e) { 
        console.log('#inner'); 
        console.log(e.currentTarget); 
        console.log(e.target); 
    }); 
</script>

以上测试输出如下:

1.当点击click here!时click会向上冒泡,输出如下:

#inner 
<a href="#" id="inner">click here!</a> 
<a href="#" id="inner">click here!</a> 
#wrapper 
<div id="wrapper">…</div> 
<a href="#" id="inner">click here!</a> 

2.当点击click here!时click会向上冒泡,输出如下:

#wrapper 
<div id="wrapper">…</div> 
<div id="wrapper">…</div> 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进