【问题标题】:Maintain hidden div selection from array after page refresh页面刷新后保持从数组中隐藏的 div 选择
【发布时间】:2012-10-25 19:34:15
【问题描述】:

我创建了一个 div id 数组,以便页面的用户可以在选择只显示一个或所有 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 show/hide resetting when page reloads,这有助于我理解,但我仍然无法让它与我的数组一起使用。我是否需要为每个单独的 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';
}
});

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

【问题讨论】:

    标签: javascript jquery html refresh hidden


    【解决方案1】:

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

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

    .hideMe {
        display:none
    }
    

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

    【讨论】:

    • 感谢您的回复。但是,这并不能解决在页面刷新后保留选择的问题,不是吗?我的隐藏/显示脚本工作正常,我只是希望能够在刷新后保留选择,例如使用 cookie 或会话存储。
    • 您问“我需要为每个单独的 id 设置规则,还是使用数组有更优雅的解决方案?” ——这回答了这个问题。您可能需要考虑使用“url hash”技术来解决保持状态的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 2021-04-24
    • 2014-03-26
    • 2019-03-25
    相关资源
    最近更新 更多