每次 jQuery 绑定(bind)到点击事件时,我如何创建一个函数来 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/
关于javascript - 每次 jQuery 绑定(bind)到点击事件时,我如何创建一个函数来 console.log 详细信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8502664/