开发者

How can I iterate over cookies using jquery (or just javascript)?

I am using the "Cookie Plugin" by Klaus Hartl to add or update cookies at $(document).ready. I have another event that is supposed to iterate all the cookies and do something with the value of each cookie. How can I it开发者_运维问答erate over the collection of cookies and get the id and value of each?

I'm thinking something like this:

$.cookie.each(function(id, value) { 
            alert('ID='+id+' VAL='+value); 
        });


If you just want to look at the cookies it's not that hard without an extra plugin:

$.each(document.cookie.split(/; */), function()  {
  var splitCookie = this.split('=');
  // name is splitCookie[0], value is splitCookie[1]
});


well it's rather easy in plain javascript:

var keyValuePairs = document.cookie.split(';');
for(var i = 0; i < keyValuePairs.length; i++) {
    var name = keyValuePairs[i].substring(0, keyValuePairs[i].indexOf('='));
    var value = keyValuePairs[i].substring(keyValuePairs[i].indexOf('=')+1);
}


The other solution does create white spaces before the name, which gives hard to debug errors.

var keyValuePairs = document.cookie.split(/; */);
for(var i = 0; i < keyValuePairs.length; i++) {
    var name = keyValuePairs[i].substring(0, keyValuePairs[i].indexOf('='));
    var value = keyValuePairs[i].substring(keyValuePairs[i].indexOf('=')+1);
    ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜