所以我正在做的是一个脚本,它在您编写时在登录按钮中实时显示您的用户名。我现在的问题是脚本也显示密码,显然这是不能容忍的。
另外,我该如何改进我的代码,以便当我在用户名字段中使用退格键时,我可以按住它并且它仍然实时显示在该按钮中。目前它只是从按钮中删除一个字符,因为我正在使用 window.onkeyup
。
现在这是我的代码。
HTML:
<html>
<head>
<title>Assignment7</title>
<script src="usr_script.js"></script>
</head>
<body onload="onload()">
<form method="post" action="login.php">
<table border="0" style="width: 10%; height: 10%" align="center">
<tr>
<td colspan="2" style="text-align: center;">
<h1><b>Murphy's Blog<br></b></h1>
</tr>
<tr>
<td style="text-align: center;">Username:</td>
<td style="text-align: center;">
<input type="text" name="usrname" onfocus="usr_name();" />
</td>
<br>
</tr>
<tr>
<td style="text-align: center;">Password:</td>
<td style="text-align: center;">
<input type="password" name="pwd" id="pwd" />
</td>
<br>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<input type="submit" name="login" id="button" />
</td>
</tr>
</table>
</form>
</body>
</html>
这是脚本文件:
function usr_name() {
var key = "";
window.onkeyup = function (e) {
if (e.keyCode == 8) {
var lenght = key.lenght;
key = key.slice(0, -1);
} else {
key = key + String.fromCharCode(e.keyCode);
}
write(key);
}
}
function write(key) {
key = key.toLowerCase();
key = key.charAt(0).toUpperCase() + key.slice(1);
var text = "Login with name: " + key;
document.getElementById("button").value = text;
}
function onload() {
document.getElementById("button").value = "Login with name: ";
}
最佳答案
这解决了密码问题:
http://jsfiddle.net/isherwood/5CuLy/1/
<input type="text" name="usrname" id="usrname" ...
document.getElementById('usrname').onkeyup = function (e) {
这个更简单的版本修复了退格重复问题(虽然不是实时的,但我不确定它在这里是否重要):
http://jsfiddle.net/isherwood/5CuLy/2/
function usr_name() {
var key;
document.getElementById('usrname').onkeyup = function (e) {
key = this.value;
write(key);
}
}
function write(key) {
key = key.toLowerCase();
key = key.charAt(0).toUpperCase() + key.slice(1);
var text = "Login with name: " + key;
document.getElementById("button").value = text;
}
关于javascript - 如何改进我的脚本不显示带有用户名字段的密码字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24003187/