表显示/隐藏记住选择

时间:2015-04-13 11:09:39

标签: php cookies jscript

我是初学者,在我的php页面中使用jscript使用以下代码隐藏/显示表:

<script type="text/javascript">
function setTable(what){
if(document.getElementById(what).style.display=="none"){
document.getElementById(what).style.display="block";
}
else if(document.getElementById(what).style.display=="block"){
document.getElementById(what).style.display="none";
}
}
</script>

并使用:

显示/隐藏table2
<a href="#" onclick= "setTable('table2')"><img src="/icons/index.png" width="55" height="55"></a>

我的问题是,在使用此代码时,如果有任何浏览器活动,表将重置为默认状态。我很难在用户显示/隐藏表后启用它,即使在页面内进行刷新/导航时它也应该继续。我知道我应该使用cookies但不知道。请有人指导我。 感谢

1 个答案:

答案 0 :(得分:0)

使用cookie来存储表状态。

<script type="text/javascript">

var tableState = getCookie("table2state");
if (tableState != "") {
    document.getElementById('table2').style.display = tableState;
}

function setTable(what) {
    if (document.getElementById(what).style.display == "none") {
        document.getElementById(what).style.display = "block";
        setCookie(what + 'state', "block", 365);
    } else if (document.getElementById(what).style.display == "block") {
        document.getElementById(what).style.display = "none";
        setCookie(what + 'state', "none", 365);
    }
}

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}
</script>