我正在使用JQuery cookie来更改背景的颜色。我也同时更改徽标图像,但在页面重新加载时,我仍在试图弄清楚如何让cookie保留徽标图像。到目前为止,我有使用cookie的背景,但无法弄清楚如何使用cookie保留选定的主题徽标图像。
到目前为止我的代码是:
<div class="main bg1">
<img id="logo-img" class="green-img" src="http://i1294.photobucket.com/albums/b601/danomatic11/logo-green.png" alt="logo"/>
<h2>Lorem ipsum dolor sit</h2>
</div>
<p>Choose a theme:</p>
<ul class="theme-switcher">
<li class="green"> </li>
<li class="purple"> </li>
<li class="rust"> </li>
</ul>
$("li.green").click( function(){ $
(".main").removeClass('bg2 , bg3').addClass("bg1");
$('#logo-img').attr('src', 'http://i1294.photobucket.com/albums/b601/danomatic11/logo-green.png');
$.cookie('mycookie','bg1');
$.cookie('mycookieimg','green-img');
});
等等......
正如您所看到的,当单击<li>
并重新加载页面时,我在背景颜色上设置了一个cookie,我正在尝试对徽标图像执行相同操作。它可以在点击时替换图像,但我无法在页面重新加载时设置cookie。
答案 0 :(得分:2)
试试这个......
$(document).ready(function(){
/*
On click the theme is changed for the image and the logo. So far I have JQuery cookie working to keep the background color that was selected even after page reload.
To do: retain the selected theme logo using coookie.
*/
$("li.green").click( function(){ $
(".main").removeClass('bg2 , bg3').addClass("bg1");
$('#logo-img').attr('src', 'http://i1294.photobucket.com/albums/b601/danomatic11/logo-green.png');
$.cookie('mycookie','bg1');
$.cookie('mycookieimg','logo-green');
});
$("li.purple").click( function(){ $
(".main").removeClass("bg1 , bg3").addClass("bg2");
$('#logo-img').attr('src', 'http://i1294.photobucket.com/albums/b601/danomatic11/logo-purple.png');
$.cookie('mycookie','bg2');
$.cookie('mycookieimg','logo-purple');
});
$("li.rust").click( function(){ $
(".main").removeClass("bg1 , bg2").addClass("bg3");
$('#logo-img').attr('src', 'http://i1294.photobucket.com/albums/b601/danomatic11/logo-rust.png');
$.cookie('mycookie','bg3');
$.cookie('mycookieimg','logo-rust');
});
if ($.cookie('mycookie')) {
var $imgsrc = $.cookie('mycookieimg');
$('.main').addClass($.cookie('mycookie'));
$('#logo-img').attr('src','http://i1294.photobucket.com/albums/b601/danomatic11/'+$imgsrc+'.png');
}
});
答案 1 :(得分:1)
if ($.cookie('mycookie')) {
$('.main').addClass($.cookie('mycookie'));
//-- set image src/class via $.cookie('mycookieimg') value
}
我看不到尝试设置img属性的位置。另外,为什么不使用透明的PNG并通过图像显示div的背景?