javascript获取启动onclick函数的html元素

javascript getting the html element that fired the onclick function

本文关键字:html 元素 函数 onclick 获取 启动 javascript      更新时间:2024-01-04

我有以下html代码:

<a class="button-dashboard-save" href="#" onclick="return interface.saveChanges();">Save</a>

在interface.saveChanges()中,我想得到激发该函数的元素对象,我指的是整个元素。

问候,

如果我理解正确,您希望引用interface.saveChanges中的锚元素<a>。在这种情况下,您可以直接将this关键字传递给函数。代码应该看起来像:

<a class="button-dashboard-save" href="#" 
   onclick="return interface.saveChanges(this);">Save</a>

在内联onclick中使用this。它将在您的案例中传递当前单击的元素。

<a class="button-dashboard-save" href="#" onclick="return interface.saveChanges(this);">Save</a>

定义一个事件处理程序函数(为了简单起见,使用jquery):

$(".button-dashboard-save").click ( function ( eve ) {
    return interface.saveChanges ( eve.target );
});

这为interface.saveChanges提供了作为参数的触发元件。

你的html稍微简化了:

 <a class="button-dashboard-save" href="#">Save</a>