如何获取对事件的源元素的引用

How to get a reference to the event's source element

本文关键字:事件 元素 引用 何获取 获取      更新时间:2023-09-26

在事件侦听器中,我需要对作为事件源的元素的引用。我怎么得到它?

对于任何在一段时间内做JavaScript的人来说,这应该是不费吹灰之力的。

包括事件处理程序在内的所有函数都在全局范围内,因此隐式成为 DOM window对象的一部分。

function WireHandlers() {
    $('.updateResourceImageButton').click(UpdateResourceLinkClickedHandler);
}
function UpdateResourceLinkClickedHandler() {
  // I would like a reference to the hyperlink/anchor
  // that was actually clicked, i.e. the hyperlink that
  // was the source of this event
  // would the keyword 'this' evaluate to the element I need?
  // or will it evaluate to the HTML DOM 'window' object
  // in this context?
}
$(document).ready(function () { WireHandlers(); });

当您通过引用传递函数时,您仍然可以正常访问参数。因此,event.targetthis将是UpdateResourceLinkClickedHandler函数中单击的元素:

function UpdateResourceLinkClickedHandler(e) {
    // clicked element as a native DOM element
    var foo = e.target; 
    var bar = this;
    // jQuery object containing clicked element
    var $foo = $(this);
}

请注意,此示例中的foobar将包含相同的值。

我认为你可以这样做

$(this)

这也是来自jquery文档

var target = $( event.target );

如本页 http://api.jquery.com/event.target/并查看本文以获取更多信息 http://www.pkshiu.com/loft/archive/2009/01/understanding-this-this-and-event-in-a-jquery-callback-function