search

Home  >  Q&A  >  body text

javascript - jquery If you first use off to unbind an event and then on to bind the event, it will not work?

Click to view the mobile version demo

Main JS code

    //显示侧边栏
    $("#drap").click(function(){
        $(".footer_fixed").hide();
        $(".sidebar").animate({right:"0%"});
        $(".modelBlack").fadeIn("fast");
        $(document).off("click");   //先解除事件绑定
        $(document).on("click");   //再绑定事件,就不起作用了?
    })

    //点击空白区域关闭
    $(document).off("click").click(function(e){
      var _con = $('.sidebar');   // 设置目标区域
      if(!_con.is(e.target) && _con.has(e.target).length === 0){
           $(".sidebar").animate({right:"-72%"});
           $(".modelBlack").fadeOut("fast");
      }
      $(".footer_fixed").show();
    });

Function Description:

question:

Problem 1: Clicking on the blank area cannot close the directory on the right;
Problem 2: If you do not use $(document).off("click"); when you click the directory button, the following two will be triggered at the same time event, the right column will be opened/closed continuously;

習慣沉默習慣沉默2766 days ago970

reply all(4)I'll reply

  • 滿天的星座

    滿天的星座2017-06-12 09:30:16

    The binding element is wrong, just bind the mask

      //点击空白区域关闭
        $(".modelBlack").click(function(e){
          var _con = $('.sidebar');   // 设置目标区域
          if(!_con.is(e.target) && _con.has(e.target).length === 0){
               $(".sidebar").animate({right:"-72%"});
               $(".modelBlack").fadeOut("fast");
               // console.log(2);
                $(".footer_fixed").show();
          }
        });

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-06-12 09:30:16

    $("#drap").on("click",function(e){
         e.stopPropagation();//阻止事件冒泡
         //巴拉巴拉
    });
    
    $(document).on("click",function(){
        //balabala
    });

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-12 09:30:16

    //Show sidebar

    $("#drap").click(function(){
        $(".footer_fixed").hide();
        $(".sidebar").animate({right:"0%"});
        $(".modelBlack").fadeIn("fast");
        //点击空白区域关闭
        $(document).off("click").on("click",function(e){
           var _con = $('.sidebar');   // 设置目标区域
           if(!_con.is(e.target) && _con.has(e.target).length === 0){
               $(".sidebar").animate({right:"-72%"});
               $(".modelBlack").fadeOut("fast");
          }
          $(".footer_fixed").show();
        });
    })
    

    reply
    0
  • 巴扎黑

    巴扎黑2017-06-12 09:30:16

    Similar questions

    Please refer to the adoption information

    reply
    0
  • Cancelreply