使用JS獲取SessionStorage的值
獲取sessionStorage的意義
首先獲取它是為了將獲得的信息輸出或者alert();讓人容易看到,
其次,在靜態(tài)頁面中,如果使用sessionStorage就相當(dāng)于在動態(tài)頁面里連接了數(shù)據(jù)庫一樣
例如:我上一篇所做的為button按鈕添加回車事件的項(xiàng)目中所用到的可以使用js中的sessionStorage獲取頁面輸入的信息,也可以獲得后臺計(jì)算所得的數(shù)據(jù),并且顯示出來。
廢話不多說,看代碼重要:
具體實(shí)現(xiàn)
<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="請輸入真實(shí)姓名"/> <input type="password" id="password" placeholder="請輸入密碼(默認(rèn)密碼123456)"/> <input type="button" value="登錄考試" onclick="login()">
以上代碼是獲取username的值并傳到下一個界面
并且獲得password的值與事先設(shè)置好的對比,不同就是錯誤 就不可以登錄
<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>
獲取前段頁面輸入的值并且顯示至對應(yīng)的位置
<div id="yhm"></div>
并且判斷是否有sessionStorage的值,如果沒有,自動返回登錄頁面,并做出相應(yīng)的提示
點(diǎn)擊事件觸發(fā)后清空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>
當(dāng)點(diǎn)擊id為esc的按鈕時觸發(fā)clear事件
<button id="esc" style="background-color: #FF0000">退出考試系統(tǒng)</button>
則自動返回登錄界面
總結(jié)
以上所述是小編給大家介紹的使用JS獲取SessionStorage的值,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
echarts多條折線圖動態(tài)分層的實(shí)現(xiàn)方法
這篇文章主要介紹了echarts多條折線圖動態(tài)分層的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05uniapp使用webview嵌入vue頁面及通信實(shí)現(xiàn)方式
項(xiàng)目中有需要嵌入其他H5的頁面的業(yè)務(wù)需求,這篇文章主要給大家介紹了關(guān)于uniapp使用webview嵌入vue頁面及通信實(shí)現(xiàn)方式的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01HTML使用js給input標(biāo)簽增加disabled屬性的方法
最近項(xiàng)目上提出一個經(jīng)常遇到的需求,點(diǎn)擊新增時input可輸入,點(diǎn)擊編輯時input置灰,下面這篇文章主要給大家介紹了關(guān)于HTML使用js給input標(biāo)簽增加disabled屬性的相關(guān)資料,需要的朋友可以參考下2024-06-06JS基于面向?qū)ο髮?shí)現(xiàn)的拖拽功能示例
這篇文章主要介紹了JS基于面向?qū)ο髮?shí)現(xiàn)的拖拽功能,涉及javascript面向?qū)ο笈c頁面元素動態(tài)操作的相關(guān)技巧,需要的朋友可以參考下2016-12-12JS實(shí)現(xiàn)兼容各種瀏覽器的獲取選擇文本的方法【測試可用】
這篇文章主要介紹了JS實(shí)現(xiàn)兼容各種瀏覽器的獲取選擇文本的方法,可實(shí)現(xiàn)鼠標(biāo)拖動選擇文本的同時,下方顯示區(qū)同步實(shí)時顯示選中內(nèi)容的功能,涉及javascript響應(yīng)鼠標(biāo)事件及頁面元素動態(tài)操作技巧,需要的朋友可以參考下2016-06-06