Textarea maxlength IE问题

时间:2012-03-16 05:34:20

标签: jquery internet-explorer

我有这个代码,它适用于所有浏览器,但它不适用于IE。 不确定原因。有人有任何想法吗? 以下是Jsfiddle demo

上的演示
<textarea name="detail" class="words"></textarea>

$(words).keyup(function() {

            var maxWords = 24;
            var a = words.val().split(' ');
            var word=0, i=0;
            for(; (i<a.length) && (word<maxWords); ++i)
            if(a[i].length) ++word;
            maxL = a.splice(0,i).join(' ');

            var wordsLimit = words.val().split(" ").length;
            var charLimit = $.trim($(".words"));
            maxLength = maxL.replace(/\s/g, '');

            if(wordsLimit > 25) {
                $(this).next('span').remove();
                $(this).after('<span class="error">*Max word limit 25</span>');
                $(this).attr('maxlength',maxL.length)
            } else {
                $(this).removeAttr('maxlength') 
            }
        });

2 个答案:

答案 0 :(得分:1)

来自Kevin B&#39:s http://jsfiddle.net/5Zd3V/9/

$(words).keypress(function(e) {
    var maxWords = 4,
        wordLimit = words.val().match(/\S+/g),
        isNoneWhite = String.fromCharCode(e.which).match(/\s/i),
        limitReached = wordLimit ? wordLimit.length >= maxWords && isNoneWhite : false;

    words.next('span.error').text(
        limitReached ? '*Max word limit ' + maxWords : ''
    );

    return !limitReached;
});​

认为你们唯一缺少的是确保输入的字符不会创建一个新单词(isNonWhite)

答案 1 :(得分:0)

IE不支持textareas上的maxlength属性。

试试这个(更新):

words.keypress(function(e) {
    var maxWords = 4;
    var wordCount = words.val().match(/\S+/g);
    wordCount = wordCount ? wordCount.length : 0;
    if (wordCount > maxWords && e.which != 8) {
        words.next('span').remove();
        words.after('<span class="error">*Max word limit ' + maxWords + '</span>');
        return false;
    }
});​

演示:http://jsfiddle.net/5Zd3V/8/