jQuery-记住图像状态 [英] JQuery - Remember Image State
问题描述
我的网站上有一张可以点击的图片.单击后,jquery会更改图像并运行ajax查询.
I have an image on my site that can be clicked. Once clicked jquery changes the image and runs an ajax query.
我不想让图像状态被记住.它将为ON或OFF. 我知道我应该使用Cookie或本地存储,但是我需要确保它可以与某些可能使用较旧的浏览器一起使用,并且我不知道如何保存状态.
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");
});
});
我创建了 JFiddle 来显示图像的切换和确实可以,但是有人可以指出正确的方向来记住页面重新加载或刷新时的图像状态.
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.
谢谢
推荐答案
使用本地存储:
jsfiddle: http://jsfiddle.net/9CkDq/1/
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");
});
});
使用Cookie:
jsfiddle: http://jsfiddle.net/9CkDq/9/
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");
});
});
您可以使用会话存储特定会话的状态,并使用db永久保存状态.
you can use sessions to store the state for a particular session and db to save state for ever.
这篇关于jQuery-记住图像状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!