防止粘贴长度大于给定限制的文本

jQuery: prevent pasting of text of length greater than given limit

本文关键字:文本 大于      更新时间:2023-09-26

我有一个文本区,我限制了可以输入的单词数量。它工作良好,并阻止用户输入额外的文本,但它有一个问题。如果用户复制/粘贴到文本区域,他们可能会违反规则。我不知道如何着手解决这个问题。

我知道它可能与onpaste事件有关,但我如何将其实现到这段代码中:

jQuery(document).ready(function($) {
    var max = 100;
    $('#text<? echo $rowcat2['cfid'];?>').keypress(function(e) {
        if (e.which < 0x20) {
            return;
        }
        var value<? echo $rowcat2['cfid'];?> = $('#text<? echo $rowcat2['cfid'];?>').val();
        var regex = /'s+/gi;
        var wordCount<? echo $rowcat2['cfid'];?> = value<? echo $rowcat2['cfid'];?>.trim().replace(regex, ' ').split(' ').length;
        if (wordCount<? echo $rowcat2['cfid'];?> == max) {
            // Reached max, prevent additional.
            e.preventDefault();
        } else if (wordCount<? echo $rowcat2['cfid'];?> > max) {
            // This doesn't work.
            this.value = this.value.substring(0, max);
        }
    });         
});

好的-我只会添加粘贴事件与建议的超时和重构你的代码。

未测试,但类似以下内容:

jQuery(document).ready(function ($) {
    var max = 100;
    $('#text<? echo $rowcat2['
    cfid '];?>').on('keypress', function (e) {
        if (e.which < 0x20) {
            return;
        }
        processWordCount(this, e);
    }).on('paste', function () {
        setTimeout(function () {
            processWordCount(this, e);
        }, 100);
    });
    function processWordCount(that, e) {
        var value <? echo $rowcat2['cfid']; ?> = $('#text<? echo $rowcat2['
        cfid '];?>').val();
        var regex = /'s+/gi;
        var wordCount <? echo $rowcat2['cfid']; ?> = value <? echo $rowcat2['cfid']; ?> .trim().replace(regex, ' ').split(' ').length;
        if (wordCount <? echo $rowcat2['cfid']; ?> == max) {
            // Reached max, prevent additional.
            e.preventDefault();
        } else if (wordCount <? echo $rowcat2['cfid']; ?> > max) {
            // This doesn't work.
            that.value = that.value.substring(0, max);
        }
    }
});

捕获粘贴输入的问题是,实际的输入似乎被延迟到分配给所述粘贴的事件处理程序被触发之后。

解决方法是使用setTimeout() -计时器甚至可以设置为0ms。通过将函数放在堆栈的底部,这将导致该函数被延迟。HTML5中的最小超时实际上是4ms,但可以设置0ms的超时:

setTimeout(function () {
    /* do whatever */
}, 0)

这个答案与我给你的另一个答案非常相似。您可以考虑通过

将它们绑定在一起
var checkInput = function () {
    /* the logic goes here */
}
$("#selector").keypress(checkInput);
$("#selector").on("paste", checkInput);
关键的区别在于使用了setTimeout:

JavaScript

var maxWords = 10;
$("#myText").on("paste", function (event) {
    setTimeout(function () {
        var text = $("#myText").val().split(" ");
        while (text.length > maxWords) {
            text.pop();
        }
        $("#myText").val(text.join(" "));
    }, 0)
})

<p>Enter no more than 10 words:</p>
<textarea id="myText"></textarea>
CSS

textarea {
    width: 300px;
    height: 100px;     
}
<标题>小提琴