使用js获取sessionStorage

获取sessionStorage的意义

首先获取它是为了将获得的信息输出或者alert();让人容易看到,
其次,在静态页面中,如果使用sessionStorage就相当于在动态页面里连接了数据库一样
例如:我上一篇所做的为button按钮添加回车事件的项目中所用到的可以使用js中的sessionStorage获取页面输入的信息,也可以获得后台计算所得的数据,并且显示出来。
废话不多说,看代码重要:

具体实现

<script type="text/javascript">
        function login(){
            var username=window.document.getElementById("username").value;
            var password=window.document.getElementById("password").value;
            if(password=="123456")
            {
                window.sessionStorage.setItem("username", username);
                window.location.href="../index1.html";
            }else{
                alert("密码错误请输入正确的密码,例如:123456!");
                return false;
            }
        }
</script>
.
.
.
<input type="text" id="username" class="11" placeholder="请输入真实姓名"/>
.
.
.
<input type="password" id="password"  placeholder="请输入密码(默认密码123456)"/>
.
.
.
<input type="button" value="登录考试" onclick="login()">

以上代码是获取username的值并传到下一个界面
并且获得password的值与事先设置好的对比,不同就是错误 就不可以登录

  <script>
      $(function () {
          var username= window.sessionStorage.getItem("username")
          $("#yhm").html("登录用户:"+username)
          $("#name").html(username)
          if(window.sessionStorage.getItem("username")===null){
              alert("您还没有登录,请登录后重试!")
              window.location.href="Pages/index.html";
          }
          $("#esc").on("click",function(){
              window.sessionStorage.clear();
              window.location.href="Pages/index.html";
          });
    })

  </script>

获取前段页面输入的值并且显示至对应的位置
<div id="yhm"></div>
并且判断是否有sessionStorage的值,如果没有,自动返回登录页面,并做出相应的提示

点击事件触发后清空sessionStorage的值

<script>
$("#esc").on("click",function(){
              window.sessionStorage.clear();
              window.location.href="Pages/index.html";
          });
</script>

当点击id为esc的按钮时触发clear事件
<button id="esc" style="background-color: #FF0000">退出考试系统</button>
则自动返回登录界面

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.几种基本数据类型?复杂数据类型?值类型和引用数据类型?堆栈数据结构? 基本数据类型:Undefined、Nul...
    极乐君阅读 10,999评论 0 106
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,978评论 25 709
  • 俗话说:“千寒易除,一湿难去。湿性黏浊,如油入面”,“湿气”可说是现代人健康大敌之一,许多疾病都是由体内湿气太重引...
    迦恩阅读 4,919评论 0 0
  • 八万年前,我是精灵族唯一成神的精灵,我的名字叫映雪,是精灵族众人仰慕的公主,那时的精灵族只听从神的号令,亦 是这世...
    未慈阅读 3,987评论 6 8
  • 文/柯临 “半年多经常这么迟下班,既没加班费也没见工资多高。才工作没多久就这样!以后还怎么了得啊?”晚上10点多,...
    临公子的后花园阅读 3,793评论 3 13

友情链接更多精彩内容