所以即时通讯有点新的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