Catch only keypresses that change input?

前端 未结 4 709
栀梦
栀梦 2020-11-28 09:39

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 chan

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 10:09

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

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

    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 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.

    Putting it all together (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!");
    });
    

提交回复
热议问题