刷新页面时,我想保留一些 Javascript。执行此操作的最佳方法看起来像使用 jquery.cookie.js,但从文档中我仍然不清楚如何将 Jquery 存储为 cookie 记住的变量。
代码的 JS Fiddle 在这里:http://jsfiddle.net/sXz3h/2/
我想做的事情如下:
- 记住最近触发的 jQuery 状态的详细信息,以便它们在页面刷新时加载。
html 看起来像
<div class="beans">
<div class="range">
<h2>Page title</h2>
<div class="blends blend-two">
<img src="http://placehold.it/100x100" alt="Medium number 2">
<div class="blend-text hide">
<h3 class="blend-heading">Medium</h3>
<p class="blend-blurb">Medium roasted. A little more complex with a bigger mouth feel. Clean finish.</p>
</div>
</div>
<div class="blends blend-three">
<img src="http://placehold.it/100/100" alt="Strong number 3">
<div class="blend-text hide">
<h3 class="blend-heading">Strong</h3>
<p class="blend-blurb">Full city roast colour with a chocolate flavour. Rich in taste.</p>
</div>
</div>
</div>
</div>
还有 JS:
$('.blend-two').click(function() {
$('.blends').each(function() {
$('.blends').find('.blend-text').addClass('hide');
$('.blends').find('img').css('opacity', '.5');
});
$(this).find('.hide').removeClass('hide');
$('.blend-two img').css('opacity', '1');
$('a.active, h2').css('color', '#e0812f');
if ($("div").hasClass("beans")) {
$('.range').css('background-image', 'url(http://placehold.it/600x600)');
} else if ($("div").hasClass("freeze-dried")) {
$('.range').css('background-image', 'url(http://placehold.it/700x700)');
} else {}
});
$('.blend-three').click(function() {
$('.blends').each(function() {
$('.blends').find('.blend-text').addClass('hide');
$('.blends').find('img').css('opacity', '.5');
});
$(this).find('.hide').removeClass('hide');
$('.blend-three img').css('opacity', '1');
$('a.active, h2').css('color', '#cf701c');
if ($("div").hasClass("beans")) {
$('.range').css('background-image', 'url(http://placehold.it/800x800)');
} else if ($("div").hasClass("freeze-dried")) {
$('.range').css('background-image', 'url(http://placehold.it/900x900)');
} else {}
});
Jquery.cookie.js 是执行此操作的最佳方法吗?如果是,我该如何存储状态?
最佳答案
如果您使用 HTML5,localStorage 会更简单。
设置它
localStorage.setItem('itemName', 'itemValue')
获取值
localStorage.getItem('itemName')
删除它
localStorage.removeItem('itemName')
关于javascript - 如何在 cookie 中存储触发的 jquery CSS 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23505764/