我正在尝试根据一个表单元格中的更改自动更新另一个表单元格。用户有名字、姓氏和用户名。用户名由首字母+姓氏组成。我当前的代码是:
<html>
<head>
<script type = "text/javascript">
function updateUsername(){
var firstname = document.getElementById("tdFirstname").firstChild.firstChild.nodeValue;
var lastname = document.getElementById("tdLastname").firstChild.firstChild.nodeValue;
var username = document.getElementById("tdUsername").innerHTML = firstname + lastname;
}
</script>
</head>
<body>
<table id = 'confirm'>
<tr>
<th>Firstname</th>
<td id = 'tdFirstname'>
<div onkeypress = 'updateUsername()' contentEditable>
Johnny
</div>
</td>
</tr>
<tr>
<th>Lastname</th>
<td id = 'tdLastname'>
<div onkeypress = 'updateUsername()' contentEditable>
Sppleseed
</div>
</td>
</tr>
<tr>
<th>Username</th>
<td id = 'tdUsername'>
JSPPLESEED
</td>
</tr>
</table>
</body>
</html>
代码可以工作(只需要把名字和姓氏放在一起,不用担心名字的首字母),但它落后了一个字母。它不会在输入新字符后更新,这意味着如果我将lastname更新为Appleseed (就像它应该的那样),只更改一个字母没有任何效果(username仍然是Sppleseed),但当按下第二个键时,它将更改为Appleseed。我的代码有问题吗?或者我错过了在输入/删除新字符后必须更新的内容。这非常令人沮丧。
发布于 2013-02-12 01:50:12
尝试使用onkeyup
而不是onkeypress
。
当用户释放一个键时,在执行了该键的默认操作之后,将触发keyup事件。
https://stackoverflow.com/questions/14817786
复制相似问题