简体   繁体   中英

How do I find out what javascript function is being called by an object's onclick event?

How do I find out what javascript function is being called by an object's onclick event? Even better, can I then find out which included .js file that function is in?

I use Chrome's Developer Tools for this:

Google Chrome开发者工具中的事件监听器断点

Check the click box, and then click on the element on the page you want to find the handler for. If you are using jQuery (or similar library), you may have to step through their code before you get to yours.

You can do like this

With Javascript Demo on JsFiddle

div1 = document.getElementById('div1');

alert(div1.getAttribute("onclick"));​

With jQuery Demo on JsFiddle

<div id="div1" onclick="myfun();" >​

alert($('#div1').attr('onclick'))​;

You wouldn't be able to find out the file the onclick event is called from but myObject.onclick will give you the function that's being called. And no, you don't need jQuery for this.

As far as getting the name of the function, that's a little more complicated. You could try something like this, perhaps:

var myFunc = myObject.onclick, myFuncName = "";

for(prop in window) {
    if(window.hasOwnProperty(prop) && window[prop] === myFunc) {
        myFuncName = prop; // myFuncName is now the name of the function. This only works if you didn't assign an anonymous function to the click handler.
        break;
    }
}

But honestly, I think that's a little overkill.

That depends on how the event is attached.

If you're binding to onclick without something like jQuery you could do this:

var obj = document.getElementById('elementId');
console.log(obj.onclick);

I do this using this Visual Event script which neatly highlights which events are subscribed by which functions on which elements.

To find the souce of the code, simply use FireBug or similar browser developer tools to search the function name.

I have a different approach. I overload onclick function and add my debugger before the real function.

This is the element

<div id="div1">​

Write this JavaScript to developer console

var clickFn = $("#div1").click; 

$("#div1").click(function(){ 
    debugger; 
    clickFn(); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM