如何实现点击事件触发之后刷新还保存原值

下面为html 代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div{
            width: 100px;
            height: 20px;
            font-size: 12px;
        }
        p{
            line-height: 20px;
            text-align: center;
        }

        button{
            font-size: 10px;
        }

    </style>
</head>
<body>
<div><p>javascript!</p></div>
<button>点击</button>
<script src="src/dist/bulid.js"></script>
</body>
</html>

 

1. JS代码:

window.onload =function () {
    let color = localStorage.x?localStorage.x:'background:#f00';
    let Div = document.getElementsByTagName('div')[0];
    let Btn =document.getElementsByTagName('button')[0];

    Div.style = color;
    Btn.onclick = function () {
        localStorage.x = 'background:#00f';
            Div.style = localStorage.x;
    }
};

 

2.原先的 JS代码 

window.onload =function () {
    // let color = localStorage.x?localStorage.x:'background:#f00';
    let Div = document.getElementsByTagName('div')[0];
    let Btn =document.getElementsByTagName('button')[0];

    // Div.style = color;
    Div.style.background = '#f00';
    Btn.onclick = function () {
        // localStorage.x = 'background:#00f';
        //     Div.style = localStorage.x;
        Div.style.background = '#00f'
    }
};

 

解释: 2中我们没有用locaStorage 存储值,所以每一次我们刷新页面事件都会重新加载,所以每一次都会变回原先的红色。

   1中我们用locaStrage存储了值,每次加载页面是从这里面来获取数据。localStorage 方法存储的数据没有时间限制。第二天、第二周或下一年之后,数据依然可用。

   说白了就是 把值存储在一个变量color里面,然后你点击之后locaStrage就变了,由于locaStrage只有手动删除才有效,所以当你再次加载他的Div.style还是我们之前

    赋的 color值 ,以达成刷新页面之后还是第一次点击的蓝色,而不会变为红色。

 

posted @ 2017-07-30 10:11  七月会下雪  阅读(550)  评论(0编辑  收藏  举报