检测对<input type="text">的所有更改.(立即)使用 JQuery [英] Detect all changes to a <input type="text"> (immediately) using JQuery

查看:26
本文介绍了检测对<input type="text">的所有更改.(立即)使用 JQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的值可以通过多种方式改变,包括:

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.

这篇关于检测对&lt;input type="text"&gt;的所有更改.(立即)使用 JQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆