簡體   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