Creare un cookie se (e solo se) non esiste già
-
26-09-2019 - |
Domanda
Voglio:
- Verificare se un cookie con il nome di "query" esiste
- Se sì, allora non fanno nulla
- Se no, creare un cookie "query" con un valore di 1
Nota: Sto usando jQuery 1.4.2 e il jQuery Plugin biscotto
Qualcuno ha qualche suggerimento su come posso fare questo?
Soluzione
if($.cookie('query') === null) {
$.cookie('query', '1', {expires:7, path:'/'});
}
In alternativa, si potrebbe scrivere una funzione wrapper per questo:
jQuery.lazyCookie = function() {
if(jQuery.cookie(arguments[0]) !== null) return;
jQuery.cookie.apply(this, arguments);
};
Poi si avrebbe solo bisogno di scrivere questo nel codice client:
$.lazyCookie('query', '1', {expires:7, path:'/'});
Altri suggerimenti
questo ??
$.cookie('query', '1'); //sets to 1...
$.cookie('query', null); // delete it...
$.cookie('query'); //gets the value....
if ($.cookie('query') == null){ //Check to see if a cookie with name of "query" exists
$.cookie('query', '1'); //If not create a cookie "query" with a value of 1.
} // If so nothing.
che cosa volete di più ??
Simile a Jacobs risposta, ma io preferisco prova per non definito.
if($.cookie('query') == undefined){
$.cookie('query', 1, { expires: 1 });
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow