1

我有一个带有 onclick 参数的 div:

<div onclick="some_function()"></div>

如何访问函数内的事件对象?我需要它来获取 event.target

function some_function() 
{
event = event || window.event;
var target = event.target || event.srcElement;
//does not work in IE and Firefox, but works in chrome
}
4

5 回答 5

7

这边走:

<div onclick="some_function(event)"></div>

function some_function(evt) 
{
    // do something with evt (the event passed in the function call)
}

请注意,参数名称必须event在函数调用中。在事件处理程序中,您可以使用您想要的名称。

一个活生生的例子:http: //jsfiddle.net/davidbuzatto/KHyAb/

于 2012-08-19T12:47:44.570 回答
2

如果我们使用事件监听器,那么您在 'this' 中有 html 元素,在 'event' 中有事件对象。

<a id="mya" href="#">Link</a>
var myA= document.querySelector("#mya");
myA.addEventListener("click", some_function);
function some_funtion() {
  //Here the html element is: this
  //Here the event object is: event
  //event.target is not always equal to this
}
<div id="mydiv">click here <span>then here</span></div>
var myDiv = document.querySelector("#mydiv");
myDiv.addEventListener("click", other_function);
function other_function() {
    alert(this === event.target);
}    
于 2018-11-30T12:40:45.503 回答
0

使用事件到达目标。当心目标与 currentTarget 问题:

https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

   <div onclick="some_function(event)"></div>

   function some_function(event) 
   {
       // event.target is the DOM element that triggered the event
   }
于 2012-08-19T12:48:01.483 回答
0

使用 event 和 this,两者

document.querySelector("div").addEventListener("click", function(event) {

  some_function(event, this);
  
}, false);

function some_function(currentEvent, currentObject) {

  alert("Object is: " + currentObject.nodeName);
  alert("Event is: " + currentEvent.type);
  
};
<div>Click Me</div>

于 2017-12-19T13:03:13.123 回答
0
<div onclick="some_function(this, event)"></div>
function some_function(elem, e) 
{
    //You have both: html element (elem), and object event (e)
    //elem is not always equal to e.target
}

<div onclick="alert(this === event.target);">click here <span>then here</span></div>
于 2018-11-30T10:27:25.487 回答