JavaScript 不读取文本框值

标签 javascript html

我一直在开发一个简单的登录页面,我在其中接受值并将其打印回来。我用 javascript 编写了一个函数来存储文本框中的输入值。我添加了两个打印语句来检查我的程序在哪里工作。这是我的脚本。

<html>

<head>
    <link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
    <meta charset="UTF-8">

    <title>Home| Login</title>
</head>


<body>
    <script type="text/javascript">
        function init() {
            document.write("Reached Point 1");
            document.write(document.getElementById("username").value);
            var password = document.getElementById("password").value;
            document.write("Reached Point 2");
        }
    </script>
    <div class="logo"></div>
    <div class="login-block">
        <h1>Login</h1>
        <input type="text" value="" id="username" />
        <input type="text" value="" id="password" />
        <button onclick="init()">Submit</button>

    </div>
</body>

</html>

单击按钮时会打印Reached Point 1,但不会打印用户名和Reached Point 2

最佳答案

文档加载完成后,您将无法使用 document.write。如果这样做,浏览器将打开一个新文档来替换当前文档。当文档被替换时,将不会有任何函数和 HTML 元素之类的东西。而是使用 innerHTML 将 HTML 代码放入元素内。

        function init() {
            document.getElementById("description").innerHTML += "Reached Point 1";
            document.getElementById("description").innerHTML +=  document.getElementById("username").value;
            var password = document.getElementById("password").value;
            document.getElementById("description").innerHTML += "Reached Point 2";
        }
    <div class="logo"></div>
    <div class="login-block">
        <h1>Login</h1>
        <input type="text" value="" id="username" />
        <input type="text" value="" id="password" />
        <button onclick="init()">Submit</button>
        <p id="description"></p>
    </div>

关于JavaScript 不读取文本框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34650339/

相关文章:

javascript - touchend 上的延迟操作

javascript - 为什么使用导入/导出时箭头函数不起作用

python - 使用folium创建 map 后HTML页面为空白

javascript - 如何正确显示日期时间本地值

javascript - 可见光JS : Cant make network fit bootstrap panel

javascript - 如何运行这个 AJAX JavaScript 编码?

jquery - 尝试使用 jQuery 隐藏 html 表的列

javascript - 根据来自 php 脚本的作业订单安排 cron 作业的更好方法

javascript - 替换Javascript中URL中所有匹配的查询参数值

javascript - 来自模块或通过 id 的 Vuejs 模板