This question already has answers here:
JavaScript - onClick to get the ID of the clicked button
                                
                                    (15个回答)
                                
                        
                                4年前关闭。
            
                    
我们有多种具有不同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。

最佳答案

this传递给函数:

onclick="fnSubmitForm(this);"


您可以选择id

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


DEMO

编辑

好的,由于您无法编辑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);
}


DEMO

关于javascript - 如何查找在javascript中提交了哪个提交按钮的ID(无需编辑HTML如何在脚本中进行归档),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34195552/

10-12 12:48
查看更多