我找到了一篇文章https://gist.github.com/jakebresnehan/1983968,用于show hide div和html5 localstorage。但是当我戴上我的代码时,它无效。
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>
我的Html
<section class="selection-box brandSectionBox">
<div class="row">
<div class="col-lg-12">
<div class="selection-box-title">Brand</div>
<div class="radioStyle clearfix selected brandSection">
<input name="brandRadio" id="brandRadio" value="desktop" type="radio">
<label class="selection-box-label col-lg-12">
<span class="col-lg-6">Desktop </span>
<span class="col-lg-6 text-right">From $500 </span>
</label>
</div>
<div class="radioStyle clearfix brandSection">
<input name="brandRadio" id="brandRadio" value="laptop" type="radio">
<label class="selection-box-label col-lg-12">
<span class="col-lg-6">Laptop </span>
<span class="col-lg-6 text-right">From $500 </span>
</label>
</div>
</div>
</div>
</section>
<section class="firstSelected selectedSelectionBox" style="">
<div class="row">
<div class="col-lg-12">
<div id="selectedfirst" class="selectedItem"></div><div id="changeBox1" class="changeBox"> Change</div>
</div>
</div>
</section>
我的jQuery代码
<script>
$(document).ready(function($){
if (Modernizr.localstorage) {
$(".brandSection").click(function(e) {
localStorage.setItem('branding',true);
$(".firstSelected").show();
$(".brandSectionBox").hide();
});
$("#selectedfirst, #changeBox1").click(function(e) {
//alert(test);
localStorage.setItem('branding',true);
localStorage.clear();
$(".brandSectionBox").show();
$(".firstSelected").hide();
});
var is_brand = localStorage.getItem('branding');
if(is_brand){
console.log('localStorage')
$(".firstSelected").hide();
}
if(!is_brand){
console.log('no localStorage');
$(".brandSectionBox").show();
}
}
});
</script>
我不确定我在哪里做错了。
答案 0 :(得分:1)
demo的目标是
请记住刷新页面时元素的显示/隐藏
在
之前的代码中.brandSection
- &gt;点击 - &gt; .brandSectionBox
隐藏+ .firstSelected
在localStorage中显示+ branding: true
#changeBox1
- &gt;点击 - &gt; localStorage clear + .brandSectionBox
show + .firstSelected
hide 因此,当您刷新页面时,在下面的判断中,它们都默认显示
当您拥有localStorage branding
- &gt; .brandSectionBox
隐藏
no localStroage - &gt; .firstSelected
隐藏
毕竟,您的代码应该在:
之后$(document).ready(function($){
if (Modernizr.localstorage) {
$(".brandSection").click(function(e) {
localStorage.setItem('branding',true);
$(".firstSelected").show();
$(".brandSectionBox").hide();
});
$("#selectedfirst, #changeBox1").click(function(e) {
localStorage.clear();
$(".brandSectionBox").show();
$(".firstSelected").hide();
});
var is_brand = localStorage.getItem('branding');
if(is_brand){
console.log('localStorage')
$(".brandSectionBox").hide();
}
if(!is_brand){
console.log('no localStorage');
$(".firstSelected").hide();
}
}
});