如何获取调用事件处理程序的当前HTML元素

时间:2015-08-18 17:54:21

标签: javascript jquery

如何在我正在连接的事件处理程序中获取对HTML DOM元素的引用?

var dashboard =
    {
        WireHandlers : function()
        {
          $(".approveButton")
            .unbind("click")
            .click(dashboard.approve)
        },

        approve : function()
        {
          // In here, I would like a reference
          // to the HTML DOM element that was clicked

          // Also, I would like its id
        }
    }

3 个答案:

答案 0 :(得分:2)

只需在approve函数中添加一个参数(通常名为event)并在其上调用currentTarget

approve : function(event) {
  // In here, I would like a reference
  // to the HTML DOM element that was clicked
  event.currentTarget

  // Also, I would like its id
  event.currentTarget.id
}

请注意,您还可以使用this方法中的approve来引用所点击的元素。

approve : function() {
  this // or $(this) if you want to use jQuery
}

请注意,在这种情况下,targetcurrentTarget可以互换。但是,在更复杂的情况下,there are important differences between the two

答案 1 :(得分:2)

$(this)

是jQuery元素(this是DOM元素)

this不会绑定到dashboard(因为您只是将该功能作为回调提供,您必须使用例如dashboard.WireHandlers

答案 2 :(得分:0)

从这里的jquery文档: https://api.jquery.com/click/

您可以通过"此"访问该元素。变量:

  approve : function()
        {
          var elem = this;
          var id = elem.id;
        }