Finding Triggering Element of onClick function

时间:2016-07-11 20:09:48

标签: javascript jquery html

I'm working on someone's existing code. In the code there are some inline onClick events attached to some input elements, like this one:

<input type="button" id="inputID" onClick="someFunction()"/>

Problem is that I cannot edit that input's HTML, but I can edit the javascript function declaration of that function.

function someFunction(){
     //want to console log the ID of the triggering input element e.g. #inputID
}

Is there a way that I could find the ID of the triggering input within the function, without passing any parameters at the time of calling the function (as I cannot edit the HTML)

5 个答案:

答案 0 :(得分:2)

Don't use inline event handlers. Use event listeners:

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" />

答案 1 :(得分:0)

You could use the global event object to achieve this:

function someFunction() {
    var el = window.event.target;
    console.log(el.id);
}

Example fiddle

Be aware that this is may have issues in older browsers. An alternative would be to leave the someFunction() empty (as you say that you cannot remove it in the HTML) and instead assign the event handlers through unobtrusive Javascript, from which you can access the element which raised the event through the this reference.

答案 2 :(得分:0)

You can, however it's not cross browser, in IE it's

window.event.srcElement.id

In FF and Chrome, you have to pass it to the inline function like

someFunction(event)

And then you can access it from target property

event.target.id

答案 3 :(得分:0)

Since you listed in the tags that you're using jQuery, just leave the body of someFunction empty and attach an event listener to your inputs that call that function.

$('[onclick="someFunction()"]').click(function() {
    console.log(this.id);
});

https://jsfiddle.net/k8o1umo4/

答案 4 :(得分:0)

function someFunction() {
  console.log(this.id);
}

var el = document.getElementById("inputID")
//remove inline click event
el.removeAttribute("onclick");
//attach click event
el.addEventListener("click", someFunction);

在从addEventListener调用的函数中,这个&#39;现在将引用触发事件的元素。

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#The_value_of_this_within_the_handler