如何在Jquery中调用.off()之后重置事件处理程序

时间:2014-04-14 21:07:27

标签: javascript jquery mousewheel

为什么我的第二个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);
});

1 个答案:

答案 0 :(得分:4)

您的代码在mousewheel对象上注册了两个body事件处理程序。当mousewheel事件发生并且调用事件处理程序回调函数时,第一个事件处理程序然后调用$("body").off();来取消注册BOTH事件处理程序,这样您就不会得到任何未来事件。

在那个时间点,body对象上不再有任何事件处理程序。

如果您希望仅调用一次事件处理程序,则可以使用.one()。除此之外,不清楚为什么你有两个独立的事件处理程序,因此它不清楚还有什么建议。

通常,没有理由为同一事件提供两个单独的事件处理程序。无论您想做什么工作,您都可以在一个单独的事件处理程序中执行该工作。如果您只想在某些事件中执行某些工作,那么只需在该单个事件处理程序中实现逻辑,以决定在调用事件处理程序时执行哪些工作(使用if语句等)

如果您只想取消注册其中一个事件处理程序,那么您必须使用带有事件处理程序$('body').on('mousewheel', funcName);的命名函数,这样您就可以调用$('body').off('mousewheel', funcName)来取消注册该特定事件处理程序。 / p>


使用命名函数的方式如下:

$(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);

});