0

我使用以下 jquery 代码来显示在 textarea 中输入的剩余字符数,它在所有浏览器上都可以正常工作。
但是当我使用退格键并删除一些字符时,它会显示在 Mozilla 上留下了多少字符,但它不适用于 IE、Chrome、safari。

这是演示链接:http: //jsfiddle.net/ckWNM/

jQuery(document).ready(function($) {
    var max = 10;
    $('textarea.max').keypress(function(e) {
        $("#counter").html("characters left : " +(10 - this.value.length));
        if (e.which < 0x20) {
            return;   
        }
        if (this.value.length == max) {
            e.preventDefault();
        } else if (this.value.length > max) {
            // Maximum exceeded
            this.value = this.value.substring(0, max);
        }
    });
}); //end if ready(fn)
4

1 回答 1

0

更新留下的字符keyup也可以在 Chrome 中解决此问题。

jsFiddle

jQuery(document).ready(function($) {
    var max = 10;
    $('textarea.max')
        .keypress(refreshAmount)
        .keyup(refreshAmount);
}); //end if ready(fn)

function refreshAmount(e) {
    $("#counter").html("characters left : " +(10 - this.value.length));
    if (e.which < 0x20) {
        return;   
    }
    if (this.value.length == max) {
        e.preventDefault();
    } else if (this.value.length > max) {
        // Maximum exceeded
        this.value = this.value.substring(0, max);
    }
}
于 2013-03-28T11:16:02.847 回答