jQuery:检测输入字段中的更改 [英] JQuery: detect change in input field

查看:91
本文介绍了jQuery:检测输入字段中的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
jQuery:如何检测文本框的内容已更改

Possible Duplicate:
Jquery: how to detect a textbox's content has changed

我想检测用户的键盘操作何时更改了文本字段的值.它应该可以在现代浏览器中一致地工作.

I want to detect when a user's keyboard actions alter the value of a text field. It should work consistently across modern browsers.

.keypress事件的JQuery页面说不一致吗?另外,它不适用于退格键,删除等.

The JQuery page for the .keypress event says it's not consistent? Also, it doesn't work for backspace, delete etc.

我不能使用.keydown,因为它会对shift,alt和方向键等做出反应.此外,当用户按住一个键并插入多个字符时,它不会触发多次.

I can't use .keydown as it is because it reacts to shift, alt and arrow keys etc. Also, it doesn't fire more than once when the user holds down a key and multiple characters are inserted.

我缺少一种简洁的方法吗?还是应该使用.keydown并过滤出箭头键,shift等触发的事件?我主要担心的是会有一些我不知道应该过滤的键. (我几乎忘记了alt和ctrl,我想可能还有其他).但是,我如何才能检测到该键被按下并插入了多个字符呢?

Is there a concise method I'm missing? Or should I use .keydown and filter out events that are triggered by arrow keys, shift and so on? My main concern is there will be keys that I'm not aware should be filtered. (I nearly forgot about alt and ctrl, I suppose there could be others) But then how would I detect the key being held down and inserting multiple characters?

作为奖励,它可以检测到由于粘贴(包括右键单击)而引起的更改,但是我可以从

As a bonus it would detect changes due to pasting (including right-clicking) but I have the solution to that from here.

推荐答案

您可以将'input'事件绑定到文本框.这将每次触发输入更改,因此,当您粘贴某些内容(即使单击鼠标右键)时,请删除并键入任何内容.

You can bind the 'input' event to the textbox. This would fire every time the input changes, so when you paste something (even with right click), delete and type anything.

$('#myTextbox').on('input', function() {
    // do something
});

如果使用change处理程序,则仅在用户取消选择输入框(可能不是您想要的输入框)后才会触发.

If you use the change handler, this will only fire after the user deselects the input box, which may not be what you want.

这里有一个示例: http://jsfiddle.net/6bSX6/

这篇关于jQuery:检测输入字段中的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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