![](/img/trans.png)
[英]Is it safe to remove .one() event handler in jQuery by explicitly calling .off()
[英]How to reset an event handler after calling .off() in Jquery
为什么我的第二个body.on()无法正常工作? 我添加了.off(),因为如果不是两个鼠标滚轮事件都仅通过一个鼠标滚轮按下事件触发...第二个body.on()是否应该重置.off()? 我应该如何编程?
$(document).ready(function() {
$("body").on('mousewheel', function(event, delta) {
if (event.deltaY < 0) {
if (!$(".both").hasClass('rotated')) {
$(".both").css('transform', 'rotate(180deg)');
setTimeout(function() { $(".both").addClass('rotated') }, 1000);
}
}
$("body").off();
});
$("body").on('mousewheel', function(event, delta) {
if (event.deltaY < 0) {
if ($(".both").hasClass('rotated')) {
alert("a");
}
}
});
});
我为问题添加了一个可行的解决方案,以防万一有人需要,这全都归功于所选答案
$(document).ready(function() {
function handleWheel(event) {
if (event.deltaY < 0) {
if (!$(".both").hasClass('rotated')) {
$(".both").css('transform', 'rotate(180deg)');
setTimeout(function() { $(".both").addClass('rotated') }, 1000);
}
}
// disengage just this event handler and no others
$("body").off('mousewheel', handleWheel);
};
function handleWheelNoche(event) {
if (event.deltaY < 0) {
if ($(".both").hasClass('rotated')) {
setTimeout(function() { $(".black").addClass('noche') }, 1000);
}
}
};
$("body").on('mousewheel', handleWheel);
$("body").on('mousewheel', handleWheelNoche);
});
您的代码在body
对象上注册了两个mousewheel
事件处理程序。 当发生mousewheel
事件并且调用了事件处理程序回调函数时,第一个事件处理程序将调用$("body").off();
这将同时注销两个事件处理程序,因此您不会再收到任何事件。
到那时,您在body
对象上不再有任何事件处理程序。
如果希望事件处理程序仅被调用一次,则可以使用.one()
。 除此之外,还不清楚为什么要有两个单独的事件处理程序,因此尚不清楚建议什么。
通常,没有理由为同一事件使用两个单独的事件处理程序。 无论您想做什么工作,都可以在一个事件处理程序中完成。 如果只想在某些事件期间执行某些工作,则只需在单个事件处理程序内部实现逻辑,以决定在调用该事件处理程序的任何时间都要进行哪些工作(使用if
语句等)。
如果只想注销其中一个事件处理程序,则必须在事件处理程序$('body').on('mousewheel', funcName);
使用命名函数$('body').on('mousewheel', funcName);
因此您可以调用$('body').off('mousewheel', funcName)
来注销该特定事件处理程序。
使用命名函数的工作方式如下:
$(document).ready(function() {
function handleWheel(event) {
if (event.deltaY < 0) {
if (!$(".both").hasClass('rotated')) {
$(".both").css('transform', 'rotate(180deg)');
setTimeout(function() { $(".both").addClass('rotated') }, 1000);
}
}
// disengage just this event handler and no others
$("body").off('mousewheel', handleWheel);
}
$("body").on('mousewheel', handleWheel);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.