jQuery Code for click event
I attach a click handler to a button on my page. Is there anyway to find out what code is using jQuery?
$("#dreport").click(function() {
var str = "hello";
});
Is there a anyway to get the var str = "hello开发者_C百科"
in the firebug debugger, or anywhere?
$("#dreport").attr("click")
But I only see [native code] where the body should be.
console.log(str);
Or you can create your own JQuery-logger.
jQuery.fn.log = function (logMe) {
console.log("%s says: %o", logMe, this);
return this;
};
And then call it like;
$('#btn').log("logged!");
You can also set breakpoints in firebug and inspect the variable contents in real-time.
try with this code:
jQuery.fn.collectHandlers = function(event) {
var ret = [],
events = $(this).data('events');
if (event in events) {
for (var id in events[event]) {
if (events[event][id] instanceof Function && events[event][id].toString) {
ret.push(events[event][id].toString());
}
}
}
return ret;
}
they you can type this in firebug console: $('#btn').collectHandlers('click');
. That will return array of functions attached as event listeners (via jQuery's bind
family methods) for 'click' event.
If what you want to show up in the log is: "hello" then do as Björn says. However if you want to output the logic in your function to the firebug console you can do like this:
$(document).ready(function(){
var clickFunction = function(){
var str = "hello";
console.log(clickFunction);
};
$("#dreport").click(clickFunction);
});
This will show up in the firebug console as "function()" and if you click on it you will be taken to the function code in the source. You can also name the click function itself to e.g. "foo", to make it show up as "foo()" in firebug, like this:
var clickFunction = function foo(){
var str = "hello";
console.log(clickFunction);
};
Of course you can also use firebug's built in profiler in the console. Just click on profile, then click the element you want to profile, and then click profile again. This will output all function calls triggered when you clicked on your element.
$("#dreport").attr("click") is probably not what you think it is - jQuery uses the event model of the DOM (and even if it didn't, the attribute would be called "onclick" ;)
You could look at FireQuery that adds jQuery info to FireBug - including info about attached events.
And don't forget, you can type jQuery expressions into the FireBug console, and see the results, and $("#btn").click() will fire the click event.
精彩评论