[英]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? 如何找出对象的onclick事件调用的javascript函数? Even better, can I then find out which included .js file that function is in?
更好的是,我可以找出哪个函数包含的.js文件?
I use Chrome's Developer Tools for this: 我使用Chrome的开发人员工具:
Check the click
box, and then click on the element on the page you want to find the handler for. 选中
click
框,然后单击要查找其处理程序的页面上的元素。 If you are using jQuery (or similar library), you may have to step through their code before you get to yours. 如果您使用的是jQuery(或类似的库),则可能需要在访问代码之前逐步执行它们。
You can do like this 你可以这样做
With Javascript Demo on JsFiddle 在JsFiddle上使用Javascript 演示
div1 = document.getElementById('div1');
alert(div1.getAttribute("onclick"));
With jQuery Demo on JsFiddle 在JsFiddle上使用jQuery Demo
<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. 您将无法找到调用onclick事件的文件,但
myObject.onclick
将为您提供正在调用的函数。 And no, you don't need jQuery for this. 不,你不需要jQuery。
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. 这取决于
event
的附加方式。
If you're binding to onclick
without something like jQuery you could do this: 如果你没有像jQuery那样绑定
onclick
你可以这样做:
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. 我这样做是使用这个Visual Event脚本,它整齐地突出显示哪些事件由哪些元素的哪些函数订阅。
To find the souce of the code, simply use FireBug or similar browser developer tools to search the function name. 要查找代码的源代码,只需使用FireBug或类似的浏览器开发人员工具来搜索函数名称。
I have a different approach. 我有一个不同的方法。 I overload onclick function and add my debugger before the real function.
我重载onclick函数并在真正的函数之前添加我的调试器。
This is the element 这是元素
<div id="div1">
Write this JavaScript to developer console 将此JavaScript写入开发人员控制台
var clickFn = $("#div1").click;
$("#div1").click(function(){
debugger;
clickFn();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.