如何在我正在连接的事件处理程序中获取对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
}
}
答案 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
}
请注意,在这种情况下,target
和currentTarget
可以互换。但是,在更复杂的情况下,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;
}