如何检查是否在 jquery 中使用 .on 处理事件?
例如,我为按钮单击事件添加了一个事件处理程序:
$(document).on("click", "#button", function(event) {
alert("Handled buttonclick event!");
});
现在我想检查是否处理了事件以防止再次分配相同的事件处理程序。
如何检查是否在 jquery 中使用 .on 处理事件?
例如,我为按钮单击事件添加了一个事件处理程序:
$(document).on("click", "#button", function(event) {
alert("Handled buttonclick event!");
});
现在我想检查是否处理了事件以防止再次分配相同的事件处理程序。
由于您正在委派文档 - 您需要检查文档的事件处理程序
$._data(document,'events') // will return all event handlers bound to the document
然后你可以检查你想要的事件..例如点击
var events = $._data(document,'events').click; // all click events
$.each(events,function(i,v){ // loop through
v.selector; // will give you all the selectors used in each delegated event
});
每个对象将包含以下内容
对象 {type: "click", origType: "click", data: undefined, handler: function, guid: 2…} 数据:未定义 指导:2 处理程序:函数(事件){ 命名空间:“” 需要上下文:假 origType: "点击" 选择器:“#button” 类型:“点击” __proto__: 对象
这是假设您的委托事件已绑定到文档对象。所以在这种情况下,您“必须”知道事件处理程序实际绑定到哪个元素。其他答案可能会更好
所以这个方法不会知道
$('body').on("click", "#button", function(event) {
alert("Handled buttonclick event!");
});
或者
$('parentelement').on("click", "#button", function(event) {
alert("Handled buttonclick event!");
});
如果你想add a button click once only
你可以使用one()之类的,
$("#button").one("click",function(event) {
alert("Handled buttonclick event!");
});
or manually
你可以通过setting
一个variable
like来检查
var countClicked=0;
$(document).on("click", "#button", function(event) {
alert("You clicked button "+ (++countClicked) + " times");
});