jQuery函数,用于在粘贴文本时限制基于单词计数的文本输入 [英] jQuery function to limit text entry based on word-count not working while pasting text

查看:78
本文介绍了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.

The work of this code is to count the number of words and limit them going up 200.

当我们输入textarea它工作正常,它很重要,当它达到200时它不允许写更多,但当我复制粘贴代码时,它继续200以上,我怎么能纠正这个?

When we type in the textarea it works fine, and it counts and when it reaches 200 it does not allow to write more, but when i copy paste the code, it keeps going above 200, how can i correct this?

这里是小提琴

http://jsfiddle.net/aVd4H/

提前致谢

推荐答案

首先,您的代码更正已更新 这里

First of all, your code correction is being updated here

这里 是一个关于复制粘贴的字数限制的演示,您可以将其集成到您的代码中。

and here is a demo for word limit on copy paste you can integrate it in your code.

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

your complete code according to your requirement HERE

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

call your am_cal() function at the end.

这篇关于jQuery函数,用于在粘贴文本时限制基于单词计数的文本输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆