在第一種方法中,使用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
}
}
在第二種方法中,使用HTMLInputElement
實例的value
屬性,低於回撥功能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 - 實現Event接口的對象通常作爲第一個參數傳遞給事件處理函數。在上面的代碼中,我已經在第二種方法中分配了回叫而不是事件處理程序。因爲沒有說明onkeypress
屬性值必須是事件處理程序的文檔。
OK,什麼是複雜的是,當你第二次按鍵時,它會顯示第二個方法中的第一個值?這與第一種方法如何工作? – overexchange
'document.getElementById('charInput').value'不顯示被按下的值,它顯示文本框的當前值。因此,當文本框中有一個字符並再次按下某個鍵時,它會顯示一個字符。 – dutchdukes
是的,我明白,當文本框中有一個字符,然後再次按下一個鍵時,就會顯示出一個字符。是什麼讓'document.getElementById('charInput')。值「在按下第二個字符後立即顯示第一個字符?這是我的問題 – overexchange