如何在 window 调整大小时 unbind/off jQuery 事件

How to unbind/off jQuery event when window resize

我正在尝试在 window 大于 490 时删除 jquery 事件。但是,unblind() 或 off() 元素不会停用 window 小于 490px 时激活的操作。为什么是这样?有谁知道将选择 return 恢复到其原始状态的方法吗?

$(document).ready(function(){

    $(window).resize(function(){
    if ($(window).width()<490) {
    $("#shown").unbind().click(function(){
        event.preventDefault();
        $("body div hidden").toggle('slow');
    });
    }

    else if ($(window).widht()>=490) {
        $("#shown").unbind();
        $("body div hidden").unbind();
    }
    });
});

</script>

这里是你如何实现你想要的,下面的代码将根据屏幕尺寸取消绑定隐藏事件。

$(document).ready(function()
{
var eventPresent = false;
$(window).resize(function()
{
 console.log("current width : ", $(window).width());
 
if ($(window).width()<490 && eventPresent == false) 
{ 
 $("#shown").unbind().click(function(event)
 {
   event.preventDefault();   
   $("#divText").toggle('hide');
 });
 eventPresent  = true;
}    
else if ($(window).width()>=490 && eventPresent == true) 
{            
   $("#shown").unbind();
   $("#divText").show()  
   eventPresent = false;     
 }
  });
});

 
 <script   src="https://code.jquery.com/jquery-2.2.4.min.js"   integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="   crossorigin="anonymous"></script>

 <a id="shown">click me to hide text</a>
   
<div id="divText">
                
You can not toggle me if screen is more than 490 px wide
         
</div>
 

P.S 运行 全页模式下的代码段。