我正在处理某人的现有代码。在代码中有一些内联的 onClick 事件附加到一些输入元素,比如这个:
<input type="button" id="inputID" onClick="someFunction()"/>
问题是我无法编辑该输入的 HTML,但我可以编辑该函数的 javascript 函数声明。
function someFunction(){
//want to console log the ID of the triggering input element e.g. #inputID
}
有没有一种方法可以在函数中找到触发输入的 ID,而无需在调用函数时传递任何参数(因为我无法编辑 HTML)
最佳答案
不要使用内联事件处理程序。使用事件监听器:
function someFunction(event) {
// Use `this` or `event.currentTarget` to get the current target
console.log(this.id);
}
document.getElementById("inputID").addEventListener('click', someFunction);
<input type="button" id="inputID" value="Click me" />
关于javascript - 查找 onClick 函数的触发元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38315377/