登录屏幕页面getter和setter

时间:2014-03-13 19:17:27

标签: javascript html

任何人都可以帮助我吗?基本上我需要一个页面,要求在我的网站的第一页上提供用户名。这将允许您进入主页。如何在主页被覆盖的那一刻在主页上使用该人的姓名,只有一个白页以及此前人们在屏幕上输入的内容?

登录页面代码

<link href="CSS.css" rel="stylesheet" type="text/css" />
<div id="image">
    <img src="../images/logo.jpg"/>
</div>
<div id="login">
    <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> 
</head>
<body>
    <center>   
        <!-- INLCUDING `ONSUBMIT` EVENT + ACTION URL --> 
        <form name="myform" onsubmit="tosubmit();" action="index.html">

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

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

主页代码

<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(" "+mytext);
            }

</script>


<body onload="init();">

</body>

1 个答案:

答案 0 :(得分:0)

document.write正在覆盖该页面。你不应该使用它, 请参阅规范中的warning

  

警告!此方法具有非常特殊的行为。在某些情况下,   此方法可以在解析器时影响HTML解析器的状态   正在运行,导致DOM与源不对应   文档的大小(例如,如果写入的字符串是字符串   &#34; <plaintext>&#34;或&#34; <!--&#34;)。在其他情况下,通话可以清除   首先是当前页面,就像调用document.open()一样。还有更多   在这种情况下,方法被忽略,或抛出异常。要做   更糟糕的是,这种方法的确切行为在某些情况下可以   取决于网络延迟,这可能导致非常严重的故障   很难调试。 由于所有这些原因,强烈使用此方法   泄气

你的情况就是这个:

  

在其他情况下,通话可以先清除当前页面,就像调用document.open()一样。

为避免这种情况,您可以使用DOM方法:

document.body.appendChild(document.createTextNode(mytext));