根据我的经验,input type="text" onchange事件通常只发生在你离开(模糊)控件之后。

有办法迫使浏览器触发onchange每次文本字段内容的变化?如果不是,那么“手动”跟踪这种情况的最佳方法是什么?

使用onkey* events是不可靠的,因为您可以右键单击字段并选择粘贴,这将在没有任何键盘输入的情况下更改字段。

setTimeout是唯一的方法吗?丑:-)


当前回答

我认为在2018年最好使用输入事件。

-

正如WHATWG规范所描述的(https://html.spec.whatwg.org/multipage/indices.html#event-input-input):

当用户更改值时向控件触发(参见 改变事件)

-

下面是一个如何使用它的例子:

<input type="text" oninput="handleValueChange()">

其他回答

您也可以使用按下键、按上键和按下键事件。

使用oninput而不是onchange。

index . html

<html>
  <head>
    <title>title here</title>
    <script src="index.js"></script>
  </head>
  <body>
    <input oninput="onclickhandler(this)"></input>
  </body>
</html>

script.js

function onclickhandler(e) {
  console.log(e.value);
}

更新:

参见Another answer(2015)。


2009年原文答案:

你想让onchange事件触发按下键,模糊和粘贴?这是魔法。

如果你想在他们输入时跟踪更改,使用"onkeydown"。如果你需要用鼠标捕捉粘贴操作,请使用“onpaste”(IE, FF3)和“oninput”(FF, Opera, Chrome, Safari1)。

在Safari上<textarea>破碎。使用textInput代替

“输入”对我很有用。

var searchBar  = document.getElementById("searchBar");
searchBar.addEventListener("input", PredictSearch, false);

下面的代码为我工作良好的Jquery 1.8.3

HTML: <输入类型=“文本”id=“myId”/>

Javascript/JQuery:

$("#myId").on('change keydown paste input', function(){
      doSomething();
});