检查localStorage是否等于value,隐藏元素

时间:2016-07-08 09:21:26

标签: javascript jquery html5 css3

这是我的第二个问题,所以我希望它能解决所有问题。我不知道很多javascript,因此无法准确地使我的代码工作。我尝试了很多不同的代码,但无法修复它。括号中的所有内容都是我想要的但却无法完成的工作。我想要总结一下:

-if按钮1被按下:将localStorage.thing1设置为0

-if按钮2被按下:将localStorage.thing1设置为1

-if localStorage.thing1 == 0,隐藏thingtext1。否则,显示thingtext1

<!DOCTYPE html>
<html>
<body>
<p id="thingtext1">Here Is Some Text</p>
<button id="thing1" onclick="(set value of thing1 to 0 to localStorage)">Hide</button>
<button id="thing1" onclick="(set value of thing1 to 1 to localStorage)">Show</button>

<script>
(ONLOAD)
if (localStorage.getItem("thing1") === "0") {
(HIDE(#thingtext1))
}
else{
if (localStorage.getItem("thing1") === "1"){
(SHOW(#thingtext1))
}
}
(SET thing1 to localStorage)
</script>

</body>
</html>

如果你能帮助我。 三江源。

2 个答案:

答案 0 :(得分:1)

尝试这样做:

<p id="thingtext1">Here Is Some Text</p>
<button id="thing1" onClick="localStorage.setItem('thing1', '0')">Hide</button>
<button id="thing1" onClick="localStorage.setItem('thing1', '1')">Show</button>

<script>
    $(function () {
      $(window).bind('storage', function (e) {
        if (localStorage.getItem("thing1") == "0") {
            $("#thingtext1").hide();
        }else if (localStorage.getItem("thing1") == "1"){
            $("#thingtext1").show();
        }
      });
    });
</script>

下面,

$(window).bind('storage', function (e) {

将执行LocalStorage的值更改。

答案 1 :(得分:0)

<p id="thingtext1">Here Is Some Text</p>
<button id="thing1" onclick="storeLS('0')">Hide</button>
<button id="thing1" onclick="storeLS('1')">Show</button>

<script type="text/javascript">
    function storeLS(num){
        localStorage.setItem("thing1", num);
        showRhide();
    }

    function showRhide(){
        if (localStorage.getItem("thing1") == "0") {
            $("#thingtext1").hide();
        }else if (localStorage.getItem("thing1") == "1"){
            $("#thingtext1").show();
        }
    }

    $(document).ready(function(){
        showRhide();
    });

</script>