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

时间:2013-10-09 12:44:32

标签: javascript jquery

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

对于任何一段时间使用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(); });

2 个答案:

答案 0 :(得分:2)

当您通过引用传递函数时,您仍然可以正常访问参数。因此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都包含相同的值。

答案 1 :(得分:1)

我认为你可以这样做

$(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