2013-07-13 72 views
0

所以即時通訊有點新的JavaScript和jQuery仍然如此我堅持這個小問題。 這裏的問題是「currentId」變量。 這個變量在滾動事件期間獲取一個值,但是即使在滾動事件已經過去並且在下一個滾動事件insted它只是返回null或未定義的事件之後,我仍然需要它保留。jquery中的持久變量

任何人都可以在這裏指出我正確的方向嗎?因爲iv一直在讀一天,現在哈哈哈。

$("#content").on("scroll resize", function(){ //on scroll 

    var pos=$("#frontpage").offset(); //take front page position in variable 

    $('.page').each(function(){ //for each div with a class of page 

     if(pos.top >= $(this).offset().top && pos.top < $(this).next().offset().top){ //if this divs position is in the correct range 

      if (currentId != $(this).attr('id')|| typeof currentId == 'undefined') { //if currentId Var is diffrent from this divs id or is undefined 

       var currentId = $(this).attr('id'); //set currentId Var to this divs id 

       $(this).addClass("foo"); //add class foo to this div 

      }else{ 
          //Else do nothing 
      }; //endIfElse 

     }else{ 
      $(this).removeClass("foo");  //Else remove the foo class from this div 
     };          //endIfElse 

    });        //end each 

}); 
+0

'$ currentId'爲空,它沒有價值的但 –

+2

在事件處理程序之外聲明該變量。 'var currentId = ...; $('#content#)。on(...);' – millimoose

+1

另外'typeof(foo)==='undefined''是一點點代碼味道,應該指向你這個解決方案。而不是檢查變量是否存在,您應該在**需要之前在適當的位置創建一個具有一些初始值**的值。 – millimoose

回答

0

爲什麼不乾脆把var currentId根本談不上任何功能或處理的?只要頁面顯示,它就不會消失。

現在爲了使它真正的持久,您可以存儲和讀取cookie(使用document.cookie)。

+0

由於某種原因,它仍然回到未定義我需要分配給var的值,以保持它 –

1

此代碼不是一般的大,但解決您的特定問題,把變量的聲明的代碼塊之外:

var currentId; 
$("#content").on("scroll resize", function() { //on scroll 
    var pos = $("#frontpage").offset(); //take front page position in variable 
    $('.page').each(function($currentId) { //for each div with a class of page 
     if (pos.top >= $(this).offset().top && pos.top < $(this).next().offset().top) { //if this divs position is in the correct range 
      if (currentId != $(this).attr('id') || typeof currentId == 'undefined') { //if currentId Var is diffrent from this divs id or is undefined 
       currentId = $(this).attr('id'); //set currentId Var to this divs id 
       $(this).addClass("foo"); //add class foo to this div 
      } else { 
       //Else do nothing 
      }; //endIfElse 
     } else { 
      $(this).removeClass("foo"); //Else remove the foo class from this div 
     }; //endIfElse 
    }); //end each 
}); 
+0

由於某種原因,它仍然返回undefined我需要分配給var的值,以保持它 –