簡體   English   中英

jquery中的持久變量

[英]Persistent variables in jquery

所以我有點新的javascript和jquery仍然所以我堅持這個小問題。 這里的問題是“currentId”變量。 這個變量在滾動事件期間獲取一個值但是我需要它在滾動事件已經過去之后保持並且在下一個滾動事件期間被考慮到它只是返回null或未定義。

任何人都可以指出我在正確的方向嗎? 因為我現在讀了一天哈哈哈。

$("#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

});

為什么不簡單地將var currentId放在任何函數或處理程序之外? 只要顯示頁面,它就不會消失。

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

這段代碼一般不太好,但為了解決您的具體問題,請將變量的聲明放在代碼塊之外:

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
});

暫無
暫無

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

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