我如何创建一个函数,每次jQuery绑定到单击事件时,它都会详细记录console.log

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

本文关键字:单击 事件 console log 记录 jQuery 创建 何创建 每次 函数 一个      更新时间:2023-09-26

我如何创建一个函数,每次jQuery绑定到点击事件时都将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(),因此调用它也将触发日志事件。

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