jQuery函数,用于在粘贴文本时限制基于单词计数的文本输入

时间:2013-09-09 07:38:54

标签: javascript jquery

这是jquery代码

var max_count = 200;
$(document).ready(function () {
var wordCounts = {};
$("#word_count").keyup(function () {
    var matches = this.value.match(/\b/g);
    wordCounts[this.id] = matches ? matches.length / 2 : 0;
    var finalCount = 0;
    $.each(wordCounts, function (k, v) {
        finalCount += v;
    });
    var vl = this.value;
    if (finalCount > max_count) {
        vl = vl.substring(0, vl.length - 1);
        this.value = vl;
    }
    var countleft = parseInt(max_count - finalCount);

    $('#display_count').html(finalCount);
    $('#count_left').html(countleft);
    am_cal(finalCount);
}).keyup();
});

此代码的工作是计算单词数量并限制它们上升200.

当我们输入textarea它工作正常,它计数,当它达到200它不允许写更多,但当我复制粘贴代码,它继续超过200,我怎么能纠正这个? / p>

这里是小提琴

http://jsfiddle.net/aVd4H/

提前致谢

2 个答案:

答案 0 :(得分:3)

首先,您的代码更正为updated here

here 是复制粘贴上字数限制的演示,您可以将其集成到代码中。

jQuery(document).ready(function($) {

    function limits(obj, limit){

        var text = $(obj).val(); 
        var length = text.length;

        if(length > limit){
            $(obj).val(text.substr(0,limit));
        } else {
            /**
             * Alerts the user of the remaining characters.
             * I do alert here, but you can do any other thing you like.
             */
            alert(limit - length + " characters remaining!");
        }
    }

    $('textarea').keyup(function() {
        limits($(this), 20);
    });
});

根据您的要求提供完整的代码 HERE

最后调用你的am_cal()函数。

答案 1 :(得分:2)

 var max_count = 200;
$(document).ready(function () {
    var wordCounts = {};
    $("#word_count").keyup(function () {
        CheckAndUpdateWordCount();
    });
});

将您的逻辑放在一个通用的方法中。在keyup事件和afterpaste事件中调用该方法。

function CheckAndUpdateWordCount()
{
       var Myelement = $("#word_count");
       var matches = Myelement .value.match(/\b/g);
        wordCounts[Myelement.id] = matches ? matches.length / 2 : 0;
        var finalCount = 0;
        $.each(wordCounts, function (k, v) {
            finalCount += v;
        });
        var vl = Myelement.value;
        if (finalCount > max_count) {
            vl = vl.substring(0, vl.length - 1);
          Myelement.value = vl;
        }
        var countleft = parseInt(max_count - finalCount);

        $('#display_count').html(finalCount);
        $('#count_left').html(countleft);
        am_cal(finalCount);
}


//Custom event After paste
$('HTML').live('paste', function (e) {
    e = $.extend({}, e, { type: 'afterpaste' });
    window.setTimeout(function () { $(e.target).trigger(e); }, 0);
});

使用上述方法。

$("#word_count").bind('afterpaste', function (e) {

//call a method to check 
//call the method here to check the word count after pasting any content.
CheckAndUpdateWordCount();
});