如何在javascript中查找提交按钮的ID(无需编辑HTML如何在脚本中存档)

如何在javascript中查找提交按钮的ID(无需编辑HTML如何在脚本中存档),javascript,dom,Javascript,Dom,我们有多个具有不同ID但相同onclick函数的表单 例如 <input type="button" id="a" value="SUBMIT" onclick="fnSubmitForm();"> <input type="button" id="b" value="SUBMIT" onclick="fnSubmitForm();"> <input type="button" id="c" value="SUBMIT" onclick="fnSub

我们有多个具有不同ID但相同onclick函数的表单

例如

<input type="button" id="a"  value="SUBMIT"  onclick="fnSubmitForm();">

<input type="button" id="b"  value="SUBMIT"  onclick="fnSubmitForm();">

<input type="button" id="c"  value="SUBMIT"  onclick="fnSubmitForm();">

如何找到提交按钮的ID。

尝试这样做

onclick="fnSubmitForm(this.id);"
并使用第一个函数参数获取值

function fnSubmitForm(id) {
  //your code
}

将此传递给函数:

onclick="fnSubmitForm(this);"
您可以选择
id

function fnSubmitForm(el) {
  console.log(el.id);
}

编辑

好的,因为您不能编辑HTML,这里有一个仅脚本的解决方案:

// pick up the input elements with type=button
var buttons = document.querySelectorAll('input[type="button"]');

// add click events to each of them, binding the function
// to the event
[].slice.call(buttons).forEach(function (el) {
  el.onclick = fnSubmitForm.bind(this, el);
});

function fnSubmitForm(el){
  console.log(el.id);
}

在onclick中添加如下函数

<input type='button' id='a' value='submit' onclick='fnSubmitForm()'/>
<input type='button' id='b' value='submit' onclick='fnSubmitForm()'/>
<input type='button' id='c' value='submit' onclick='fnSubmitForm()'/>

我们没有编辑html的权限,只有脚本的权限。然后how@GobinathMahalingam:您希望支持哪些浏览器?@FelixKling,不确定这是否是重复的,因为所有信息都不在原始问题中。请不要否决此答案,Tareq是对的。@Sarim Javaid Khan:我们没有编辑HTMl的权限,只有脚本文件的权限。那么如何找到id,而不在onClickSorry中添加“this.id”。问题中没有提到。编辑了答案。您还可以检查此元素是否与函数名的onlick属性值相同,以确保非常特殊。我已编辑了答案,请检查。
function fnSubmitForm(){
    console.log(this.document.activeElement.getAttribute("id"));
}