所以即時通訊有點新的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
});
'$ currentId'爲空,它沒有價值的但 –
在事件處理程序之外聲明該變量。 'var currentId = ...; $('#content#)。on(...);' – millimoose
另外'typeof(foo)==='undefined''是一點點代碼味道,應該指向你這個解決方案。而不是檢查變量是否存在,您應該在**需要之前在適當的位置創建一個具有一些初始值**的值。 – millimoose