在第一种方法中,使用事件处理程序KeyBoardEvent
下面的f
实例,COULD在按下键盘键后检索字符,如下所示:
<form action="#" id="sampForm" >
<input id='charInput' type='text'>
<p id="KeyData">Key press data here</p>
</form><br>
document.getElementById('charInput').onkeypress = f;
function f(event) {
var char = getChar(event || window.event)
if (!char) return false; // Special Key Pressed
document.getElementById('keyData').innerHTML = char + " was pressed";
return true;
}
function getChar(event) {
// event.which returns the key pressed
if (event.which == null) {
// Return the char if not a special character
return String.fromCharCode(event.keyCode); // IE
} else if (event.which!=0 && event.charCode!=0) {
return String.fromCharCode(event.which); // Other Browsers
} else {
return null; // Special Key Pressed
}
}
在第二种方法中,使用回调函数value
下面的HTMLInputElement
实例的f
属性,可以不在按键后检索字符,
<form action="#" id="sampForm" >
<input id='charInput' type='text'>
<p id="KeyData">Key press data here</p>
</form><br>
document.getElementById('charInput').onkeypress = f;
function f(){
document.getElementById('KeyData').innerHTML = document.getElementById('charInput').value + 'is pressed';
return true;
}
[第二种方法,当我按第一个键盘字符时,为什么document.getElementById('charInput').value
是空字符串?事件处理方法如何解决此问题?
注:w3.org/TR/DOM-Level-2-Events/events.html-实现事件接口的对象通常作为第一个参数传递给事件处理程序。在上面的代码中,我在第二种方法中分配了回调而不是事件处理程序。因为没有文档说明onkeypress
属性值必须是事件处理程序。
onkeypress
事件在用户按下键盘上的键时发生。在那个时间点,用户输入的键值是not
您缺少function f
的左括号
代码很好。函数f()缺少括号“ {”。还要确保此代码用<script>
标记括起来。也可以使用onkeyup代替onkeypress。