0

我创建了一个 div id 数组,以便页面的用户可以在选择要显示的一个 div 或所有这些 div 之间切换。我的脚本如下所示:

<script type="text/javascript">
function switchdivs(theid){
var thearray= new Array("div1", "div2", "div3");
for(i=0; i<thearray.length; i++){
  if(thearray[i] == theid || theid == "all"){
        document.getElementById(thearray[i]).style.display="block";

  }else{
document.getElementById(thearray[i]).style.display="none";
  }
}
}
</script>

我希望在页面刷新后保留用户的选择。我已经阅读了一些示例,例如页面重新加载时 Jquery 显示/隐藏重置,这有助于我的理解,但我仍然无法让它与我的数组一起使用。我是否需要为每个单独的 id 设置规则,或者是否有使用数组的更优雅的解决方案?我已经尝试过这样的事情,但正如你可能从我糟糕的脚本中看出的那样,我对 javascript 很陌生,而且很迷茫:

$(document).ready(function() {

if (sessionStorage['divselection']) {
if (sessionStorage['divselection'] === 'theid')
    $("#theid").show();
else
    $("#thearray[i]").hide();
}  

$("input[name='theid']").change(function() {
if( $("input[name='thearray[i]']:checked").val() == "theid")
{
    $("#thearray[i]").hide();
    $("#theid").show();
    sessionStorage['divselection'] = 'theid';
}
});

感谢您为我指明正确方向提供的任何帮助。

4

1 回答 1

0

CSS 类名的全部意义在于您可以将它们应用于元素。因此,不要跟踪单个 ID,而是使用类。

此外,不再隐藏和显示元素,而是再次使用类名,但将类名与实际样式相关联。如:

.hideMe {
    display:none
}

...然后您可以添加/删除为您完成所有隐藏/显示的类名。

于 2012-10-25T19:46:02.267 回答