2013-07-13 73 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的值,以保持它 –