繁体   English   中英

我怎样才能创建一个每次jQuery绑定到click事件时都会调用console.log细节的函数?

[英]How could I create a function that would console.log details every time jQuery binds to a click event?

我怎样才能创建一个每次jQuery绑定到click事件时都会调用console.log细节的函数?

就像发生这种情况时记录。

$('.classy').on('click', 'button', function(){
    console.log('clicked');
})

我试图解决为什么这些事件发射两次。

这样做的方法是使用新函数覆盖现有的on()方法。 新函数执行日志记录,然后调用旧的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);
    };

}());

请记住,所有其他事件方法( bind()live()delegate()和快捷方法( hover()click()等)都on()后台调用on() ,因此调用此方法将触发记录事件。

你可以看到这个在这里工作; http://jsfiddle.net/fJ38n/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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