尝试在文本框中按Enter键进行IE触发更改

时间:2012-11-03 14:07:31

标签: javascript jquery internet-explorer

在Chrome和FF中点击输入文本框时会触发更改,而不是在IE中,所以我试图让它做同样的事情

这就是我现在所拥有的: http://jsfiddle.net/nV4SA/8/

//fix for IE to trigger change on enter
    $("input[type=text]")
        .on("change", function(e) {
            $.data(this, "value", this.value);
        }).on("keyup", function(e) {
            if (e.which === 13 && this.value != $.data(this, "value")) {
                $(this).change();
            }
        });

此代码的唯一缺点是在IE用户命中输入更改发生,但当文本框失去焦点时将再次发生更改

1 个答案:

答案 0 :(得分:2)

如果仅在IE中触发change,它似乎无法触发blur。使用$.support测试IE。

/* false in IE.. see jQuery APU */
var changeBubble=$.support.changeBubbles;

$("input[type=text]").on("change", function(e) {
    $.data(this, "value", this.value);
}).on("keyup", function(e) {
    if (e.which === 13 && this.value != $.data(this, "value") && !changeBubble) {
        e.preventDefault();
        $(this).trigger('blur');
    }
})

DEMO:http://jsfiddle.net/nV4SA/10/

$.support API文档:http://api.jquery.com/jQuery.support/

编辑:请注意,$.support.changeBubbles在IE9中是正确的,但不是IE< 9。解决方案可能不是防弹的。虽然不满意,但您可能需要使用浏览器嗅探或尝试在$.support中查找仅适用于所有IE版本的其他支持属性