douji6940 2016-03-16 15:01
浏览 136

Javascript和传递Cookie问题

I am working on a script which takes the vertical scroll posistioning of a div container and on document unload it stores the vertical posistion within a cookie and then loads it on load.

Originally I had the following:

$('#GridViewContainer').load('claims.php', function() {
    $(this).scrollTop($(this).prop("scrollHeight") - $(this).height());
});

Which is ok if you are refreshing the page but if you are reloading the page with parameters it will lose it's position. Solution? Store it in a cookie...

However I am having issues with storing the value and loading it on load. I am using php to return all current Cookies and I can see I am setting the cookie "div_yCookie" but the content seems to be:
'div_yCookie' => string '[object Object]' (length=15)

(I am a complete Javascript and jQuery novice... No doubt it is something obvious but can someone help?

<script>
    function createCookie(name,value,days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
    }

    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }

    function eraseCookie(name) {
        createCookie(name,"",-1);
    }

    $(document).ready(function () {     
        $('#GridViewContainer').load('claims.php', function() {
            var x = readCookie('div_yCookie');
            $(this).scrollTop($(this).prop("scrollHeight") - x);
            //$(this).scrollTop($(this).prop("scrollHeight") - $(this).height());
        });
    });

    window.onbeforeunload = function(){
        var div_y = $('#GridViewContainer').scrollTop($('#GridViewContainer').prop("scrollHeight") - $('#GridViewContainer').height());
        createCookie('div_yCookie',div_y,0.5);
    };
</script> 

UPDATE It turns out it actually works when you refresh the page however it still doesn't work when you reload the page.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥30 这是哪个作者做的宝宝起名网站
    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题
    • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
    • ¥15 YoloV5 第三方库的版本对照问题
    • ¥15 请完成下列相关问题!