获取 sessionStorage 的意义
首先获取它是为了将获得的信息输出或者 alert();让人容易看到,
其次,在静态页面中,如果使用 sessionStorage 就相当于在动态页面里连接了数据库一样
例如:我上一篇所做的为 button 按钮添加回车事件的项目中所用到的可以使用 js 中的 sessionStorage 获取页面输入的信息,也可以获得后台计算所得的数据,并且显示出来.
废话不多说,看代码重要:
具体实现
以上代码是获取 username 的值并传到下一个界面
<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()">
并且获得 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 的值
当点击 id 为 esc 的按钮时触发 clear 事件
<script>
$("#esc").on("click",function(){
window.sessionStorage.clear();
window.location.href="Pages/index.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" ;
});
</script>
<button id="esc" style="background-color: #FF0000">退出考试系统</button>
则自动返回登录界面
总结
以上所述是小编给大家介绍的使用 JS 获取 SessionStorage 的值,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的.在此也非常感谢大家对脚本之家网站的支持!
您可能感兴趣的文章:
JS 中 LocalStorage 和 SessionStorage 的使用
JS 中 LocalStorage 与 SessionStorage 五种循序渐进的使用方法
来源: http://www.jb51.net/article/132729.htm