I need help with making a cookie thats going to have a lot of different values. So far I have this.
function makeCookie(key, value) {
document.cookie= key + "=" + value + "; path=/";}
//event listener to kick off the cookie function
var style1button = document.getElementById('style1');
style1button.addEventListener('click',function ()
{makeCookie('style','style1')},false);
//event listener to kick off the cookie function
var style2button = document.getElementById('style2');
style2button.addEventListener('click',function(
{makeCookie('style','style2')},false);
I am going to be adding in more and I will end up needing to make a cookie more then one style, but I am not sure how to pass through multiple key,values into the same function I have setup. Or is it literally just making up new names instead of
makeCookie(key, value)
can I do
makeCookie(key1, value1, key2, value2......)
I apologize if this is easy, I am new at this. After looking at the document.cookie info from multiple sites, I am not able to find anything that makes sense.
Though I do suggest switching to localStorage
, if you want to support variable arguments, I suggest you switch your argument to an object { key: "foo", value: "bar" }
and then use the array-like arguments
object to iterate over however many are passed:
// I usually put a comment showing an example of the argument(s) when
// allowing a variable number of arguments
function makeCookie(/* { key: "foo", value: "bar" }, { ... } */) {
for (var i = 0; i < arguments.length; i++) {
document.cookie= arguments[i].key + "=" + arguments[i].value + "; path=/";
}
}
makeCookie({ key: "foo", value: "bar" });
makeCookie({ key: "style1", value: "styleValue" }, { key: "style2", value: "styleValue2" });
I would suggest a function for clearing cookies (if you want) and one for adding cookies:
function clearCookies () {
document.cookie = "";
}
function addCookie (key, value) {
document.cookie += key + "=" + value + "; path=/";
}
Yes, you can do this: makeCookie(key1, value1, value2, value3......)
Functions in JS basically has "arguments" object. So, to achieve the above feature your makeCookie function should look like below:
function makeCookie(){
var key = arguments[0];
var value;
for (var i = 1; i < arguments.length; i++) {
var tempValue = arguments[i];
//write a logic here to represent the multiple values into one value
}
document.cookie= key + "=" + value + "; path=/";
}
Note: the above code assumes that you will always pass key as first argument while calling the function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.