一、第一种方式
案列1:
<body> <input type="text"> <button class="set">存储数据</button> <button class="get">获取数据</button> <button class="remove">删除数据</button> <button class="del">清空所有数据</button> </body> <script> var input = document.querySelector('input'); var set = document.querySelector('.set'); var get = document.querySelector('.get'); var remove=document.querySelector('.remove'); set.addEventListener('click', function () { // 当我们点击了之后,就可以把表单里面的值存储起来 var val = input.value; //sessionStorage.setItem() 括号里面的第一个值为:名字,第二个值是传过来的人 sessionStorage.setItem('uname', val) }); // 获取数据 get.addEventListener('click', function () { console.log(sessionStorage.getItem('uname'));}); // 删除数据 remove.addEventListener('click', function () { console.log(sessionStorage.removeItem('uname'));
}); </script> 二、第二种方式
案列:
<body> <input type="text"> <button class="set">存储数据</button> <button class="get">获取数据</button> <button class="remove">删除数据</button> <button class="del">清空所有数据</button> <script> var ipt = document.querySelector('input'); var set = document.querySelector('.set'); var get = document.querySelector('.get'); var remove = document.querySelector('.remove'); var del = document.querySelector('.del'); set.addEventListener('click', function() { var val = ipt.value; localStorage.setItem('username', val); }) get.addEventListener('click', function() { console.log(localStorage.getItem('username'));}) remove.addEventListener('click', function() { localStorage.removeItem('username');
}) del.addEventListener('click', function() { localStorage.clear();
}) </script> </body>
标签:function,存储,第十章,querySelector,addEventListener,var,document,数据,click From: https://www.cnblogs.com/dexue/p/16759112.html