设置和检索localstorage

时间:2015-12-09 14:27:01

标签: javascript

如果有人接受了要约,我需要将产品ID设置为本地存储,然后如果他们稍后再次访问该页面则检索该内容。如果存储的ID与当前商品产品ID匹配,则隐藏包含商品的div,以便他们无法再次利用它。

代码我必须关闭优惠框并在他们点击接受按钮时将ID设置为localstorage:

<script>
    var accepted = function() {

        var mydiv = document.getElementById('timed-container');

        if (mydiv.style.display === 'block' || mydiv.style.display === '')

            mydiv.style.display = 'none';
            var timedpid=<?php echo json_encode($_SESSION['time_limited_pid']); ?>; 
            localStorage.setItem('timedpid', timedpid);
        }
    }
</script>

然后使用此代码检查localstorage与页面加载时的当前商品ID

<script>
    if(localStorage.getItem('timedpid')) {

        var storedpid = localStorage.getItem('timedpid')
        var currentpid=<?php echo json_encode($_SESSION['time_limited_pid']); ?>;
        if (currentpid === storepid) {

            var mydiv = document.getElementById('timed-container');
            mydiv.style.display = 'none';
        }
    }
</script>

当前的产品ID存储在$ _SESSION ['time_limited_pid']中,因此在此测试中它是2092年。

单击“接受”时,商品窗口将关闭,但如果我重新加载页面,它会再次显示,因此要么不设置localstorage,要么在重新加载时没有运行正确的比较。

我正在寻求一些帮助来解决这个问题。

2 个答案:

答案 0 :(得分:3)

您使用assignment=)运算符代替comparison operator equality==)或严格相等(===

if (currentpid = storepid)  // <-- here you are asigning storepid to currentpid

使用:

if(currentpid === storepid) // <-- here you are comparing them

注意

您还使用不同的字符串来设置和获取项目:

localStorage.setItem('timedpid', timedpid); // <-- here its timedpid
// ...
localStorage.getItem('timepid');            // <-- here its timepid

答案 1 :(得分:0)

你在getItem中使用“timepid”,但是你在“timedpid”中设置了值,试试这个localStorage.getItem('timedpid')