按下键时获取值时出错

Wrong getting value when key is pressed

本文关键字:出错 获取      更新时间:2023-09-26

当键关闭时,我尝试从文本输入中获取值。

我的代码:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <input type="text" onkeydown="console.log(this.value)">
</body>
</html>

代码演示:http://jsbin.com/funexipure/1/edit?html,console,output

故障描述:
当我编写1时,我在控制台中""为值。
当我在此之后编写2时,我在控制台中"1"为值,依此类推

那么,当

键关闭时,我如何获得实际的当前值?谢谢。

您可以使用onkeyup来获取所需的输出

  <input type="text" onkeyup="console.log(this.value)">

Keyup 功能非常好,但如果通过鼠标单击粘贴值,则不起作用。

试试这个

$('input').on('input propertychange', function(){
   console.log($(this).val());
})

当您使用鼠标单击粘贴时,这也适用于键盘键入。

原因

keyup从键盘按键时检查,但无论如何propertychange更改任何属性时都可以工作。