非常非常简洁明了,有源码,可以运行。

    网上有很多关于html页面数据传送、保存的方法,但都只是方法,很少有实际样例,有也很复杂,看着头大。所以我写了两个关于html页面传送数据的源码,非常简单,希望能帮助到读者。

    都是经过实测可以运行的样例,vs、webstorm、lightly都运行过的,浏览器用谷歌的chorme浏览器,因为可以在开发者工具中看localStorage。至于所写代码每步的原理就不细说了,笔者也是才大二完,出来实习。

一、两个html页面数据传送

建立test1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
 
<body>
    <!--表单输入-->
    <form onsubmit="return validateForm()" method="post">
        <!--id可以自取改变,不一定是这个shuru-->
        <input type="text" id="shuru"><br><br>
    </form>

    <!--按键-->
    <button type="button" onclick="validateForm()" >进入</button>

    <!--将输入的数据和按键绑定,传入localStorage-->
    <script>
        
        function validateForm() {              
            var userna = document.getElementById('shuru').value;
            console.log(userna)
            localStorage.setItem("key",userna);
            window.location.href='test2.html';
        }
    </script>
</body>
 
</html>

建立test2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
 
<body>
    <!--naid也是可以自己取名的-->
    <script>
        var naid = localStorage.getItem("key"); //获取指定key本地存储的值
        document.write(naid)
    </script>
</body>
 
</html>

用chorme浏览器运行test1.html,输入数字或者汉字都可以,点击进入。

 然后就会跳转到test2.html,显示你输入的数据。右键点击检查,找Application下的Storage,点击localStorage可以查看key和value值。

二、多个html页面调用其中一个页面的输入值

其实第二个实验没什么好写的,只是为了让读者知道,将localStorage存储功能绑定在跳转界面上不是只能将数据传送给跳转的网页,其他网页需要的话也是可以访问到的。

test1.html不变,我们将test2.html改变以下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
 
<body>
    <!--naid也是可以自己取名的-->
    <script>
        var naid = localStorage.getItem("key"); //获取指定key本地存储的值
        document.write(naid)
    </script>

    <!--跳转界面按钮-->
    <br>
    <button type="button" onclick="as()" >跳转</button>
    <script>
        function as() {              
            window.location.href='test3.html';
        }
    </script>
</body>
 
</html>

只是添加了一个跳转界面按钮和button按钮的功能

建立test3.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
 
<body>
    <!--naid也是可以自己取名的-->
    <script>
        var na = localStorage.getItem("key"); //获取指定key本地存储的值
        document.write(na)
    </script>

</body>
 
</html>

test1.html的界面没有变,test2.html的界面变成了这样

 点击跳转按钮后进入test3.html界面,依然会显示我们输入的数据

 小结:

嗯嗯嗯,就这么多吧,第一次发文章,如有不好,请多多见谅。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐