jQuery .live('input) in IE not working when re

2019-05-27 05:26发布

问题:

Based on this question Fade in/out text based upon value of counter

I have the following markup:-

<textarea id="TextBox1"></textarea>
<br/>
<span id="validator" style="display:none"></span>

and the following jQuery:-

jQuery('#TextBox1').live('input', function() {

    var charLength = $(this).val().length;

    $('#validator').html(charLength + ' of 250 characters used');
    $('#validator').fadeInOrOut(!! charLength);

    if ($(this).val().length > 250) {
        $('#validator').html('<strong>You may only have up to 250 characters !</strong>');
    }

});

jQuery.fn.fadeInOrOut = function(status) {
    return status ? this.fadeIn() : this.fadeOut();
}; 

This all works fine in Firefox, but in IE, specifically when removing text from the textarea the .live() event doesn't seem to get fired.

There is a fiddle here that demonstrates the above, if you load in Firefox functionality works fine, load in IE and add some text to the textarea, then remove some text using the backspace key.

http://jsfiddle.net/general_exception/CsXU8/

EDIT using on doesent seem to make a difference, the bug still remains.

回答1:

Depending on your version of jQuery, use .on() instead of .live(), and instead of binding to input, just use keyup to catch the event

jQuery('#TextBox1').on('keyup', function() { });


回答2:

You can use keyup event instead of input which is not generally supported. Also you can use on instead of deprecated live:

jQuery(document).on('keyup', '#TextBox1', function() {
    ...
});

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



回答3:

For IE8/9, replace first line using following code

jQuery('#TextBox1').on('keyup', function() {