为什么输入对象的value属性不保存值?

问题描述 投票:0回答:3

在第一种方法中,使用事件处理程序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属性值必须是事件处理程序。

javascript event-handling dom-events keyboard-events
3个回答
1
投票

onkeypress事件在用户按下键盘上的键时发生。在那个时间点,用户输入的键值是not


0
投票

您缺少function f的左括号


0
投票

代码很好。函数f()缺少括号“ {”。还要确保此代码用<script>标记括起来。也可以使用onkeyup代替onkeypress。

© www.soinside.com 2019 - 2024. All rights reserved.