[英]Auto-Update table cell based on user input in Javascript
I'm trying to auto-update a table cell based on changes in another table cell. 我正在尝试根据另一个表格单元格中的更改自动更新表格单元格。 The user has a firstname, lastname and username.
用户具有名字,姓氏和用户名。 The username consists of first initial + lastname.
用户名由名字的首字母和姓氏组成。 My current code is:
我当前的代码是:
<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>
The code works (just putting the first and last names together, not worred about first initial yet), but its one letter behind. 该代码有效(只是将名字和姓氏放在一起,而不用担心首字母缩写),但后面要加上一个字母。 It doesn't update after a new character is entered, meaning if I update lastname to Appleseed (like it should be), just changing the one letter has no effect (username remains Sppleseed), but when a second key is pressed, it would change to Appleseed.
输入新字符后它不会更新,这意味着如果我将姓氏更新为Appleseed(应该如此),仅更改一个字母没有任何作用(用户名保持Sppleseed),但是当按下第二个键时,它将改为Appleseed。 Is it something wrong with my code?
我的代码有问题吗? or did I miss something that I should have to update after the new character has been entered / deleted.
还是我错过了输入/删除新字符后必须更新的内容。 This is very frustrating.
这非常令人沮丧。
Try using onkeyup
instead of onkeypress
. 尝试使用
onkeyup
代替onkeypress
。
The keyup event is fired "when the user releases a key, after the default action of that key has been performed." 在“用户执行了键的默认操作后释放键时,将触发keyup事件。”
http://www.quirksmode.org/dom/events/keys.html http://www.quirksmode.org/dom/events/keys.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.