前端开发jQuery输入框字数计数功能

web前端开发 美图面试题|手游前端开发需要掌握|软件开发前端和后端的区别

html 代码

<!DOCTYPE html>
<html lang=”en”>
<head>
    <meta charset=”UTF-8″>
    <title></title>
    <script src=”https://code.jquery.com/jquery-3.2.1.js”></script>
</head>
<body>
    <div class=”container”>
        <input id=”abc” value=”前端开发者“>
        <span id=”wordCountShow”></span>
    </div>
    <script>
        $.fn.extend({
            wordCount: function (maxLength, wordWrapper) {
                var self = this;
                $(self).attr(“maxlength”, maxLength);
                showWordCount();
                $(this).on(“input propertychange”, showWordCount);
                function showWordCount() {
                    curLength = $(self).val().length;
                    var leaveCount = maxLength – curLength;
                    wordWrapper.text(leaveCount + “/” + maxLength);
                }
            }
        })
        $(function () {
            $(“#abc”).wordCount(10, $(“#wordCountShow”));
        })
    </script>
</body>
</html>

html 代码

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
    <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
    <title>jquery限制输入字数,并提示剩余字数</title>
    <script src=”https://code.jquery.com/jquery-3.2.1.js”></script>
    <script type=”text/javascript”>
        function words_deal() {
            var curLength = $(“#TextArea1”).val().length;
            if (curLength > 5) {
                var num = $(“#TextArea1”).val().substr(0, 5);
                $(“#TextArea1”).val(num);
                alert(“超过字数限制,多出的字将被截断!”);
            }
            else {
                $(“#textCount”).text(5 – $(“#TextArea1”).val().length);
            }
        }
    </script>
</head>
<body>
    剩余
    <span id=”textCount”>5</span>个字
    <textarea name=”textarea” id=”TextArea1″ cols=”45″ rows=”5″ onkeyup=”words_deal();”></textarea>
</body>
</html>

前端开发页面优化|面试前端开发有哪些问题|2018前端开发面试题及答案

» 本文来自:前端开发者 » 《前端开发jQuery输入框字数计数功能》
» 本文链接地址:https://www.rokub.com/5135.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!