jquery: 监听输入框输入文字个数

function inputListener(inputElement, maxLength) {
    let flag = true;
    inputElement.on('compositionstart', function () {
        flag = false;
    });

    inputElement.on('compositionend', function () {
        flag = true;
    });

    inputElement.on('input', function () {
        setTimeout(function () {
            if (flag) {
                let textnum = inputElement.val().replace(/s+/g, "").length;
                $('.text-count .count').text(textnum);
                if (textnum < maxLength) {
                    $('.text-count .limit').text('');
                    $('.text-count .count').css('color', '#999');
                }
                if (textnum === maxLength) {
                    $('.text-count .limit').text(`您最多只能输入${maxLength}字`);
                    $('.text-count .count').css('color', '#ff3344');
                }
            }
        }, 100);
    });
}
原文地址:https://www.cnblogs.com/Nyan-Workflow-FC/p/13299242.html