我一直在开发一个简单的登录页面,我在其中接受值并将其打印回来。我用 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/