问题
I have an image on my site that can be clicked. Once clicked jquery changes the image and runs an ajax query.
I'm not looking to have the image state remembered. It will either be ON or OFF. I know I should be using cookies or local storage, but I need to make sure this works with some possibly old browsers, and I've no idea how to approach saving the state..
The code I'm using to toggle the image is :
jQuery(function(){
$(".img-swap").live('click', function() {
if ($(this).attr("class") == "img-swap") {
this.src = this.src.replace("_off","_on");
} else {
this.src = this.src.replace("_on","_off");
}
$(this).toggleClass("on");
});
});
I've created a JFiddle to show the toggling of the image and that does work, but can some one point me in the right direction for remembering the image state on a page reload or refresh.
Thanks
回答1:
using localstorage:
jsfiddle: http://jsfiddle.net/9CkDq/1/
jQuery(function(){
if(localStorage.getItem("class") =="on"){
$(".img-swap").attr("src",$(".img-swap").attr("src").replace("_off","_on")).addClass("on");
}
$(".img-swap").on('click', function() {
if ($(this).attr("class") == "img-swap") {
localStorage.setItem("class","on");
this.src = this.src.replace("_off","_on");
} else {
localStorage.setItem("class","off");
this.src = this.src.replace("_on","_off");
}
$(this).toggleClass("on");
});
});
using cookies:
jsfiddle: http://jsfiddle.net/9CkDq/9/
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
jQuery(function(){
if(getCookie("class")=="_on"){
$(".img-swap").attr("src",$(".img-swap").attr("src").replace("_off","_on")).addClass("on");
}
$(".img-swap").on('click', function() {
if ($(this).attr("class") == "img-swap") {
setCookie("class","_on");
this.src = this.src.replace("_off","_on",30);
} else {
setCookie("class","_off");
this.src = this.src.replace("_on","_off",30);
}
$(this).toggleClass("on");
});
});
you can use sessions to store the state for a particular session and db to save state for ever.
来源:https://stackoverflow.com/questions/24105293/jquery-remember-image-state