简体   繁体   English

如何使用JavaScript在Cookie中存储多个值?

[英]How to store multiple values in cookie using javascript?

I have created a dynamic list (ie, a tag inside li tag) using jQuery. 我创建了一个动态列表(即a内标签li的标签)使用jQuery。 When I click on a link in the list for the first time, it stores that index value in a cookie (using javascript). 当我第一次单击列表中的链接时,它会将索引值存储在cookie中(使用javascript)。 Next time I run the application, in onload it retrieves the index value from the cookie and displays that link in a different color. 下次运行该应用程序时,在onload它将从cookie中检索索引值,并以不同的颜色显示该链接。

How can I store multiple values in the same cookie? 如何在同一个Cookie中存储多个值? How can I maintain previous values always in getcookie() and setcookie() ? 如何始终在getcookie()setcookie()保持先前的值?

function link()
{
    $(".sidemenu li ").click(function() {        
        var index = $('li').index(this); 
        checkCookie(index);
    });
}   

function checkCookie(index)
{
    var linkindexvalue=index;

    setCookie("indexvalue",linkindexvalue,365);
}

function setCookie(c_name,value,exdays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + value;
    alert(document.cookie);
}

$(document).ready(function(){

    var username=getCookie("indexvalue");
    $(".sidemenu li:eq("+username+")").css({ 'background' : 'yellow' });
    alert(username);
});

function getCookie(c_name)
{
    alert("hj");
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++)
    {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name)
        {
            return unescape(y);
        }
    }
}

Please guide me . 请指导我。

Thanks in advance. 提前致谢。

Unless you need to support IE < 8, you should probably use localStorage rather than cookies. 除非您需要支持IE <8,否则可能应该使用localStorage而不是cookie。 In fact, there are libraries like store.js which let you forget about such browser discrepancies (the best available technology is used). 实际上,有一些像store.js这样的库,可以让您忘记浏览器之间的差异(使用了最好的可用技术)。

If you really must uses cookies, though, do not invent your own serialization format! 但是,如果您确实必须使用cookie, 请不要发明自己的序列化格式! JSON works just fine. JSON可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM