我正在使用JQuery' .one()
函数检查任何交互。
var myEvents = 'mousedown mousemove mouseup touchstart touchmove touchend mouseout';
jQuery(document).one(myEvents, function(){
//do something only once.
});
但是,一旦这些事件被解雇,我希望所有这些都能被解除。我知道我可以再次与jQuery(document).unbind(myEvents)
取消绑定,但是想知道在一次事件之后是否有一种干净的内置方式简单解除绑定。
编辑:这是一个小提琴:http://jsfiddle.net/4HkQy/6/
答案 0 :(得分:2)
你可以使用一个完全符合这个目的的函数来扩展jQuery。
jQuery.fn.extend({
oneForAll: function(events, handler) {
var that = this,
oneForAll = function() {
that.unbind(events, oneForAll);
handler.apply(this, arguments);
};
that.on(events, oneForAll);
}
});
您可以完全按照one
oneForAll
的方式使用它。
JSFiddle:Demo
答案 1 :(得分:1)
使用.off()
jQuery(document).one('mousedown mousemove mouseup touchstart touchmove touchend mouseout', function (event) {
console.log(event.originalEvent.type);
jQuery('p').append(event.originalEvent.type);
//remove all handlers
jQuery(document).off('mousedown mousemove mouseup touchstart touchmove touchend mouseout');
});
但我建议使用命名空间处理程序,这样你就不会错误地删除任何其他事件处理程序。
jQuery(document).one('mousedown.myonce mousemove.myonce mouseup.myonce touchstart.myonce touchmove.myonce touchend.myonce mouseout.myonce', function (event) {
console.log(event.originalEvent.type);
jQuery('p').append(event.originalEvent.type);
//remove all handlers
jQuery(document).off('.myonce');
});
演示:Fiddle