簡體   English   中英

如果一次加載jQuery,防止相同功能的實例

[英]Preventing instance of same function if loaded once jquery

我的網站導航需要轉換為垂直導航,因此我測量視口的寬度並將其與resizeload函數綁定在一起,然后執行menuConvert()函數。 但是在調整窗口大小時,它會導致多次執行menuConvert()函數。

我的js代碼是

$(window).bind('load resize', function(){
  width = $(window).width();
  console.log(width)
  if(width < 800){
     menuConverter(); // This is the function
  }
});

我想阻止該功能一旦執行就可以執行。

您可以取消綁定活動

$(window).bind('load resize', function(){
  width = $(window).width();
  console.log(width)
  if(width < 800){
     menuConverter(); // This is the function

     //Unbind
     $(window).unbind('load resize')
  }
});

我會建議使用.on().off()的就地.bind().unbind()分別。

你可以做類似的事情

var flag800;
$(window).bind('load resize', function () {
    if (width < 800) {
        if (flag800 !== true) {
            menuConverter(); // This is the function
            flag800 = true;
        }
    } else {
        flag800 = false;
    }
});

演示: 小提琴

使用簡單的布爾變量。

var menexe = false;
$(window).bind('load resize', function(){

      width = $(window).width();
      console.log(width)
      if(width < 800){
            if(menexe === false){
         menuConverter(); // This is the function
         menexe = true;
         }
      }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM