简体   繁体   English

jQuery复选框取消选中if语句

[英]Jquery Checkbox uncheck with if statement

I can't quite figure out why my code is not working here. 我不太清楚为什么我的代码在这里不起作用。

I have an if statements that checks if 1 or more check boxes have been checked, then if its true a function runs. 我有一个if语句,用于检查是否已选中1个或多个复选框,如果它为true,则运行一个函数。 The function allows a bar to slide down when the page scrolls to a certain height. 当页面滚动到特定高度时,该功能允许栏向下滑动。

It works when I first visit the site after a refresh. 当我刷新后第一次访问该站点时,它可以工作。 ie the bar is not visible, when I scroll, then when I check a box, it becomes visible. 即,该条不可见,当我滚动时,然后当我选中一个框时,它变为可见。

However when I uncheck the box the bar is still visible! 但是,当我取消选中该框时,该栏仍然可见!

How do I hide it, when the checkbox is unchecked? 取消选中复选框时,如何隐藏它?

I thought a line in the else statement like the below would work, but they don't ( I even tried to add an else if : 我以为else语句中的一行如下所示会起作用,但它们却行不通(如果出现以下情况,我甚至试图添加else if

$(".userbar").hide(); //OR
$(".userbar").slideUp(); //OR
$(".userbar").off();

Here is my Code: 这是我的代码:

$(document).on('change', '#est', function (e){
    // Get number of checkboxes checked.
    var counter = $('input[type="checkbox"]:checked').length;
    console.log("Checkboxs checked number: " + counter);
    e.preventDefault();
    if (counter >= 1 ) {
      $(window).scroll(function() {
          if ($(this).scrollTop() < 370)
          {
              $(".userbar").slideUp(100);
          }
          else
          {
              $(".userbar").slideDown(100);
          }
      });
    } else if (counter == 0 ){
            $(".userbar").hide();
          }
});

The first time that counter >= 1 , you bind a function to the window "scroll" event, and that function will decide if the bar will be visible or not. 第一次counter >= 1 ,您将一个函数绑定到window "scroll"事件,该函数将决定该条是否可见。 Even if later counter evaluates at zero, and you run the .hide() , the scroll handler you registered before will still be there and run again. 即使后面的counter值为零,并且您运行.hide() ,您之前注册的scroll处理程序仍将在那里并再次运行。

An easy way to fix this would be to add something like 解决此问题的一种简单方法是添加类似

else if (counter == 0 ){
    $(window).off("scroll");
    $(".userbar").hide();
}

Be aware that .off("scroll") will remove any handler for the "scroll" event. 请注意, .off("scroll")将删除“ scroll”事件的所有处理程序。 If you have others and you want to keep them, you might want to name your handler and remove it individually, like: 如果您有其他人并且想要保留他们,则可能要命名处理程序并将其单独删除,例如:

function myScrollHandler() {
    if ($(this).scrollTop() < 370)
    {
        $(".userbar").slideUp(100);
    }
    else
    {
        $(".userbar").slideDown(100);
    }
}
// ...
$(window).scroll(myScrollHandler);
// ...
$(window).off("scroll", myScrollHandler);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM