<script>
$(document).ready(function(){
$(".hide").click(function(){
$(this).next(".comm").slideToggle("fast");
return false;
});
});
</script>
<div id="com1">
<button class="hide">Hide/show</button>
<div class="comm">
Data here
</div>
</div>
<div id="com2">
<button class="hide">Hide/show</button>
<div class="comm">
Data2 here
</div>
</div>
所以我有这个代码,感谢stackoverflow回答我让它工作,但我有一个关于保存状态的问题。我尝试了一种cookie方法,但我似乎无法弄清楚如何保存状态并从cookie中加载每个div的保存值。
答案 0 :(得分:0)
使用class
代替id
。更改您的 html ,
<div id="com">
<button class="hide">Hide/show</button>
<div class="comm">Data here</div>
</div>
<div id="com2">
<button class="hide">Hide/show</button>
<div class="comm">Data2 here</div>
</div>
要保存状态,请尝试使用localStorage()
$(document).ready(function(){
if(localStorage && localStorage.getItem('activeComm')){
comm=localStorage.getItem('activeComm');
$('#'+comm).slideToggle("fast");
}
$(".hide").click(function(){
$comm=$(this).next(".comm");
$comm.slideToggle("fast");
localStorage.setItem('activeComm',$comm.attr('id'));
return false;
});
});
<强> HTML 强>
<div id="com">
<button class="hide">Hide/show</button>
<div class="comm" id="comm-1">Data here</div>
</div>
<div id="com2">
<button class="hide">Hide/show</button>
<div class="comm" id="comm-2">Data2 here</div>
</div>