[英]How could I create a function that would console.log details every time jQuery binds to a click event?
How could I create a function that would console.log details every time jQuery binds to a click event? 我怎样才能创建一个每次jQuery绑定到click事件时都会调用console.log细节的函数?
Like logging when this happens. 就像发生这种情况时记录。
$('.classy').on('click', 'button', function(){
console.log('clicked');
})
I'm trying to trouble shoot why these events are firing twice. 我试图解决为什么这些事件发射两次。
The way to do this is to overwrite the existing on()
method with a new function. 这样做的方法是使用新函数覆盖现有的on()
方法。 The new function does the logging, and then calls the old on()
implementation. 新函数执行日志记录,然后调用旧的on()
实现。
(function () {
// Store a reference to the existing bind method
var _on = jQuery.fn.on;
// Define a new implementation
jQuery.fn.on = function () {
// Do your logging, etc.
console.log("on called with " + arguments.length + " arguments");
// Don't forget to do the actual bind!
return _on.apply(this, arguments);
};
}());
Bear in mind that all the other event methods ( bind()
, live()
, delegate()
and the shortcut methods ( hover()
, click()
etc) all call on()
behind the scenes, so calls to this will fire log events as well. 请记住,所有其他事件方法( bind()
, live()
, delegate()
和快捷方法( hover()
, click()
等)都on()
后台调用on()
,因此调用此方法将触发记录事件。
You can see this working here; 你可以看到这个在这里工作; http://jsfiddle.net/fJ38n/ http://jsfiddle.net/fJ38n/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.