Javascript在另一个页面中提交表单和显示消息。

时间:2014-04-23 15:34:10

标签: javascript html submit local-storage

我有一个我正在制作的网站的登录页面,当你输入一个名字并点击提交时,它会转到下一页并说欢迎(输入的名称)但我似乎无法放任何其他页面上的文字,有什么帮助吗?

的index.html

<html>
<head>
    <title>Test</title>
    <script type="text/javascript">

        // Called on form's `onsubmit`
        function tosubmit() {
            // Getting the value of your text input
            var mytext = document.getElementById("mytext").value;

            // Storing the value above into localStorage
            localStorage.setItem("mytext", mytext);

            return true;
        }

    </script> 
<link href="stylesheet.css" rel="stylesheet" type="text/css">
</head>
<body>
    <center>   
        <!-- INLCUDING `ONSUBMIT` EVENT + ACTION URL --> 
        <form name="myform" onSubmit="tosubmit();" action="home.html">

            <input  id="mytext" type="text" name="data">
            <input type="submit" value="Submit">

        </form>
</body>
</html>

home.html的

<html>
<head>
<script>

    // Called on body's `onload` event
    function init() {
        // Retrieving the text input's value which was stored into localStorage
        var mytext = localStorage.getItem("mytext");

        // Writing the value in the document
        document.write("Welcome "+mytext+"!");
    }

</script>
<link href="stylesheet.css" rel="stylesheet" type="text/css">
</head>    

<body onLoad="init();">
<div id="container">

<div id="header">

</div>
<div id="navigation">
</div>
<div id="body">
</div>
<div id="rightcolumn">
</div>
<div id="footer">
Department of Computing
</div>
</div>

</body>

</html>

例如在页脚中查看计算机部门&#39;没有出现

1 个答案:

答案 0 :(得分:0)

文档加载完成后,您无法使用document.write()。如果您这样做,浏览器将打开一个替换当前内容的新文档,这就是您的页脚文本未显示在输出中的原因(home.html)。

使用innerHTML属性将HTML代码放在元素

因此,在 home.html 中将document.write()更改为

   document.getElementById("body").innerHTML="Welcome "+mytext+"!";  // here body name is the ID of element where you want to display your message.

此处已更新 home.html

    <html>
    <head>
    <script>

        // Called on body's `onload` event
        function init() {
            // Retrieving the text input's value which was stored into localStorage
            var mytext = localStorage.getItem("mytext");

            // Writing the value in the document
            document.getElementById("body").innerHTML="Welcome "+mytext+"!"; // <-- this will display message in a element with id "body" 
        }

    </script>
    <link href="stylesheet.css" rel="stylesheet" type="text/css">
    </head>    

    <body onLoad="init();">
    <div id="container">

    <div id="header">

    </div>
    <div id="navigation">
    </div>
    <div id="body"> <!-- message will be shown here -->
    </div>
    <div id="rightcolumn">
    </div>
    <div id="footer">
    Department of Computing
    </div>
    </div>

    </body>

    </html>