4

First off, I know this has been asked before. I'm asking again in the hopes that more recent versions of common libraries like jQuery have solved this. This may be wishful thinking, I know...

Having said that, is there a way to detect all changes (keypress, paste, autocorrect) to an <input> yet? I was using $("#myElement").bind('input propertychange', function (e) {...}); until IE9 came along and broke it (it doesn't fire on backspace/cut/delete).

There are three options that I'm aware of, all of which have drawbacks:

  1. Bind to even more events (keyup, paste, etc.) and use setTimeout to ignore duplicates.
  2. Bind to specific events based on browser detection.
  3. Bind to even more events, track the old value with jQuery.data(), and compare against it before firing the handler (as in this answer).

If there's not a "better way" yet, which of the above do you prefer, and why?

4

4 回答 4

2

作为不支持 的浏览器的后备方案oninput,您可以在字段上同时使用onkeyuponinput事件,但对事件处理程序进行去抖动以防止多次执行:

$('input').on('keyup input', debounce(function() {
  // do something
  console.log('input'):
}, 500));

var debounce = function(func, wait, immediate) {
    var timeout;
    return function () {
        var context = this, args = arguments;
        var later = function () {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};
于 2015-06-02T14:23:59.433 回答
0

尝试这个:

<input type="text" onchange="$(this).trigger('change');">

如果它有效,您可以有条件地使用.attr('onchange', '...')有问题的浏览器,以避免将您的标记与黑客行为混淆。

<script>
    <!--[if lte IE 9]>
        $('input[type=text]').attr('onchange', '$(this).trigger(\'change\')');
    <![endif]-->
</script>
于 2013-02-28T22:01:11.800 回答
0

您可以尝试按键事件。但是,我使用了blur 事件

给你一点哲学:我发现文本框会以任何方式改变我的文本的形状或形式,因为我正在输入反直觉和烦人的东西。

当然,对于诸如 3 字段 SSN 之类的东西,您想继续检查长度以将它们射击到下一个字段,但它.blur()适用于其他所有内容。

于 2013-02-28T21:42:30.017 回答
0

如果您只支持现代浏览器,是的,有一种方法可以跨浏览器只使用一个事件:input

$(myelement).on('input',function(){
    console.log(this.value);
});

如果您希望继续支持旧浏览器,则必须继续为它们使用解决方法,因为旧版本的浏览器不会被修复。

我更喜欢将 keydown 与输入配对,因为 keydown 在触发输入事件的同时触发。

于 2013-02-28T21:45:24.300 回答