检测对<input type=“text">的所有更改;(立即)使用 JQuery

2022-01-30 00:00:00 jquery javascript html

<input type="text"> 的值可以通过多种方式改变,包括:

There are many ways the value of a <input type="text"> can change, including:

  • 按键
  • 复制/粘贴
  • 用 JavaScript 修改
  • 由浏览器或工具栏自动完成

我希望我的 JavaScript 函数在任何时候被调用(使用当前输入值).而且我希望它立即被调用,而不仅仅是在输入失去焦点时.

I want my JavaScript function to be called (with the current input value) any time it changes. And I want it to be called right away, not just when the input loses focus.

我正在寻找在所有浏览器中执行此操作的最简洁、最可靠的方法(最好使用 jQuery).

I'm looking for the cleanest and most robust way to do this across all browsers (using jQuery preferably).

推荐答案

不幸的是,我认为 setInterval 中奖了:

Unfortunately, I think setInterval wins the prize:

<input type=text id=input_id />
<script>
setInterval(function() { ObserveInputValue($('#input_id').val()); }, 100);
</script>

这是最简洁的解决方案,只需 1 行代码.它也是最健壮的,因为您不必担心 input 可以获取值的所有不同事件/方式.

It's the cleanest solution, at only 1 line of code. It's also the most robust, since you don't have to worry about all the different events/ways an input can get a value.

使用 'setInterval' 的缺点似乎不适用于这种情况:

The downsides of using 'setInterval' don't seem to apply in this case:

  • 100 毫秒的延迟?对于许多应用程序来说,100 毫秒已经足够快了.
  • 增加了浏览器的负载?一般来说,在您的页面上添加大量重量级的 setInterval 是不好的.但在这种特殊情况下,无法检测到添加的页面加载.
  • 它不能扩展到很多输入?大多数页面只有少量输入,您可以在同一个 setInterval 中嗅探所有输入.
  • The 100ms latency? For many applications, 100ms is fast enough.
  • Added load on the browser? In general, adding lots of heavy-weight setIntervals on your page is bad. But in this particular case, the added page load is undetectable.
  • It doesn't scale to many inputs? Most pages don't have more than a handful of inputs, which you can sniff all in the same setInterval.

相关文章