我有以下代码。
我希望它在刷新时保持蓝色。有人可以帮我解决这个问题吗?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<style type='text/css'>
a {color: blue}
.active {color:red}
</style>
<script type='text/javascript'>
$(document).ready(function(){
$('.filters a').on('click', function() {
var data_filter = $(this).closest("a").data('filter');
if($(this).hasClass("active")) {
$(this).removeClass("active");
localStorage.setItem(data_filter,true);
}
else {
$(this).addClass("active");
localStorage.setItem(data_filter,false);
}
});
$('.filters a').each(function(){
var data_filter = $(this).closest("a").data('filter');
var checked = localStorage.getItem(data_filter);
if(checked){
$(this).addClass('active');
} else {
$(this).removeClass('active');
}
});
});
</script>
</head>
<body>
<div class="filters slide-down">
<ul class="groups inline naked right">
<li class="group">
<h3 class="text-right filter-heading trigger" data-target="#colours_filters">Colour</h3>
<ul class="naked" id="colours_filters">
<li class="filter-option"><a href="#" data-tax="colours" data-filter=".tag-colours-black-2">Black</a></li>
<li class="filter-option"><a href="#" data-tax="colours" data-filter=".tag-colours-blue">Blue</a></li>
<li class="filter-option"><a href="#" data-tax="colours" data-filter=".tag-colours-brown">Brown</a></li>
<li class="filter-option"><a href="#" data-tax="colours" data-filter=".tag-colours-gray">Gray</a></li>
</ul>
</li>
<li class="group">
<h3 class="text-right filter-heading trigger" data-target="#theme_filters">Theme</h3>
<ul class="naked" id="theme_filters">
<li class="filter-option"><a href="#" data-tax="theme" data-filter=".tag-theme-carefree">Carefree</a></li>
<li class="filter-option"><a href="#" data-tax="theme" data-filter=".tag-theme-decay">Decay</a></li>
<li class="filter-option"><a href="#" data-tax="theme" data-filter=".tag-theme-dramatic">Dramatic</a></li>
<li class="filter-option"><a href="#" data-tax="theme" data-filter=".tag-theme-family">Family</a></li>
<li class="filter-option"><a href="#" data-tax="theme" data-filter=".tag-theme-nautical">Nautical</a></li>
</ul>
</li>
</li>
</ul>
</body>
</html>
答案 0 :(得分:2)
$('.filter-option a')
,而不是$('.filters a')
。localStorage
设置true
和false
应更改其位置(true
时为false
,反之亦然)。if (checked)
实际上甚至可以用于false
值,因为checked
是String
,而不是Boolean
。所以它应该是if (checked == 'true')
$(document).ready(function()
{
$('.filter-option a').on('click', function()
{
var data_filter = $(this).data('filter');
$(this).toggleClass("active");
localStorage.setItem(data_filter, $(this).hasClass("active"));
});
$('.filter-option a').each(function()
{
var data_filter = $(this).data('filter');
var checked = localStorage.getItem(data_filter);
if (checked == 'true')
{
$(this).addClass('active');
}
});
});