仅捕获改变输入的按键?

mpe*_*pen 10 javascript jquery

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

那我该怎么办呢?

Tim*_*own 23

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

$("#testbox").on("input", function() {
    alert("Value changed!");
});
Run Code Online (Sandbox Code Playgroud)

这在IE <9中不起作用,但有一个解决方法:propertychange事件.

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

IE 9支持两者,因此在该浏览器中,最好选择基于标准的input事件.这样可方便地触发第一,所以我们可以删除处理程序propertychange第一次input火灾.

把它们放在一起(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!");
});
Run Code Online (Sandbox Code Playgroud)

  • @Mark:对于文本`<input>,你可以在几乎所有主要的东西:Safari 3 +,所有Chrome,Firefox 2 +,IE 6+(甚至可能是5),Opera等9+.对于textareas,支持不是很好. (2认同)

Jas*_*zek 8

.change()就是你所追求的

$("#testbox").keyup(function() {
   $(this).blur();
   $(this).focus(); 
   $(this).val($(this).val()); // fix for IE putting cursor at beginning of input on focus
}).change(function() {
   alert("change fired");
});
Run Code Online (Sandbox Code Playgroud)

  • `.change()`在文本框失去焦点之前不会触发.听起来他想要在按键上得到通知. (4认同)