简体   繁体   English

如何获取触发jQuery事件的对象?

[英]How to get the object which fired the event in jquery?

In javascript, we have event.srcElement that gives us the element on which some event is occured. 在javascript中,我们具有event.srcElement ,它提供了发生事件的元素。 Is there any way by which we can get this object in jQuery. 有什么方法可以在jQuery中获得此对象。

Also, 也,

function myFun(){
  alert ( $(this) ); // what do this object represent? Is it what i need ?
}

Short answer: If you're inside an event handler then yes, this is what you care about most of the time. 简短的回答:如果您在事件处理程序内部,则可以, this是您大部分时间所关心的。


Inside an event handler this refers to what you're after or if needed access the event object passed in, for example: 在事件处理程序内部, this指的是您要执行的操作或在需要时访问传入的事件对象 ,例如:

$(".element").click(function(e) {
  //this is the element clicked
  //e.target is the target of the event, could be a child element
});

For example if your click handler was actually on a parent and you clicked something inside, the anchor in this case: 例如,如果您的click处理程序实际上是在父级上,并且您单击了其中的某个内容,则本例中的锚点为:

<div id="parent"><a href="#">Test</a></div>

With this handler: 使用此处理程序:

$("#parent").click(function(e) {
  //this is the <div id="parent"> element
  //e.target is the <a> element
});

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

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