LocalStorage-通过表单保存名称-在其他页面上显示 [英] LocalStorage - save name through form - show on other page

查看:61
本文介绍了LocalStorage-通过表单保存名称-在其他页面上显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的html页面,其中有一个文本字段,要求输入用户名.我想保存用户输入的内容,然后在另一页上我想检索该名称并打个招呼+(用户名).

I have one simple html page with a text field that asks for user's name. i want to save what user enter and on another page i want to retrieve that name and say hello + (user's name).

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>LocalStorage</title>
</head>
<body>
<form>
    <p>Enter your name</p>
    <input type="text">
    <button type="submit" value="submit">Submit</button>
</form>

</body>
</html> 

第二页是第一页数据的存储位置(通过localStorage).

and the second page is where the data from first page comes (through localStorage).

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>secondPage</title>
</head>
<body>

<h1>Hello </h1>

</body>
</html>

谢谢.

推荐答案

以下是使用 sessionStorage 的建议方法.

Here's a suggested approach by using sessionStorage.

但是,您也可以将 localStorage 与相同的实现方法一起使用.它们之间的唯一区别是,即使您关闭浏览器, localStorage 也会保留数据.在这种情况下,保存 userName 我认为最好使用 sessionStorage .

However, you can also use localStorage with the same implementation method. The only differences between them is localStorage will keep the data even if you close your browser. Which in this case, saving userName I think it's better to use sessionStorage.

1.html

1.html

<form action="2.html" onsubmit="callme()">
    <p>Enter your name</p>
    <input id="tbName" type="text">
    <button type="submit" value="submit">Submit</button>
</form>
<script>
    function callme(){
        var name = document.getElementById('tbName').value;
        sessionStorage.setItem('userName', name);
    }
</script>

2.html

2.html

<h1 id="welcome"> </h1>
<script>
    window.onload = function() {
        document.getElementById('welcome').innerText = "Hello, " + sessionStorage.getItem('userName');
    };
</script>

这篇关于LocalStorage-通过表单保存名称-在其他页面上显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆