使用JS獲取SessionStorage的值


參考:https://www.jb51.net/article/132729.htm

獲取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" rel="external nofollow" ;
      }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" rel="external nofollow" rel="external nofollow" rel="external nofollow" ;
     }
     $("#esc").on("click",function(){
       window.sessionStorage.clear();
       window.location.href="Pages/index.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" ;
     });
  })
 </script>

獲取前段頁面輸入的值並且顯示至對應的位置

<div id="yhm"></div>

並且判斷是否有sessionStorage的值,如果沒有,自動返回登錄頁面,並做出相應的提示

點擊事件觸發后清空sessionStorage的值

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

當點擊id為esc的按鈕時觸發clear事件

<button id="esc" style="background-color: #FF0000">退出考試系統</button>

則自動返回登錄界面


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM