仅捕获改变输入的按键? [英] Catch only keypresses that change input?

查看:85
本文介绍了仅捕获改变输入的按键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在按键更改文本框的输入时执行某些操作。我认为 keypress 事件最适合这个,但我怎么知道它是否引起了变化?我需要过滤掉像箭头键或修饰符这样的东西...我不认为硬编码所有值是最好的方法。

I want to do something when a keypress changes the input of a textbox. I figure the keypress event would be best for this, but how do I know if it caused a change? I need to filter out things like pressing the arrow keys, or modifiers... I don't think hardcoding all the values is the best approach.

那么我应该如何是吗?

推荐答案

在大多数浏览器中,您可以使用HTML5 输入文本类型的事件< input> 元素:

In most browsers, you can use the HTML5 input event for text-type <input> elements:

$("#testbox").on("input", function() {
    alert("Value changed!");
});

这不适用于IE< 9,但有一个解决方法: propertychange 事件。

This doesn't work in IE < 9, but there is a workaround: the propertychange event.

$("#testbox").on("propertychange", function(e) {
    if (e.originalEvent.propertyName == "value") {
        alert("Value changed!");
    }
});

IE 9支持两者,因此在该浏览器中,最好选择基于标准的输入事件。这方便首先触发,因此我们可以在第一次输入触发时删除 propertychange 的处理程序。

IE 9 supports both, so in that browser it's better to prefer the standards-based input event. This conveniently fires first, so we can remove the handler for propertychange the first time input fires.

全部放在一起( jsFiddle ):

var propertyChangeUnbound = false;
$("#testbox").on("propertychange", function(e) {
    if (e.originalEvent.propertyName == "value") {
        alert("Value changed!");
    }
});

$("#testbox").on("input", function() {
    if (!propertyChangeUnbound) {
        $("#testbox").unbind("propertychange");
        propertyChangeUnbound = true;
    }
    alert("Value changed!");
});

这篇关于仅捕获改变输入的按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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