' TypeError:$(...)。characterCounter不是一个函数'在我的jquery插件中

时间:2017-05-03 09:07:55

标签: javascript jquery jquery-plugins

我正在练习jQuery插件

我创建了这个插件:

(function ($) {
    'use strict';
    $.fn.characterCounter = function () {
        return this.each(function (index, item) {
            $(item).keyup(function updateCharCounter() {
                var $me = $(this),
                    maxLength = parseInt($me.attr('maxlength'), 10),
                    charCount = $me.val().length,
                    $counter = $me.siblings('.limit');

                $counter.text('limit: ' + maxLength + ' characters. remaining: ' + (maxLength - charCount));
            });
        });
    };

})(jQuery);

和我的HTML代码:

<div class="form-group">
    <textarea id="short-message" maxlength="100" cols="8"></textarea>
    <p class="limit">limit: 100 characters</p>
</div>

<div class="form-group">
    <textarea id="short-shory" maxlength="150" cols="8"></textarea>
    <p class="limit">limit: 150 characters</p>
</div>

<div class="form-group">
    <input id="nickname" maxlength="50" size="32"/>
    <p class="limit">limit: 50 characters</p>
</div>


<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/showCharacterCharlimit.js"></script>

<script>
    $(document)
        .ready(function() {
            'use strict';
            $('textarea').characterCounter();
        });

</script>

但是给我这个错误:

  

TypeError:$(...)。characterCounter不是函数

我不知道为什么,有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

&#13;
&#13;
(function ($) {
    'use strict';
    $.fn.characterCounter = function () {
        return this.each(function (index, item) {
            $(item).keyup(function updateCharCounter() {
                var $me = $(this),
                    maxLength = parseInt($me.attr('maxlength'), 10),
                    charCount = $me.val().length,
                    $counter = $me.siblings('.limit');

                $counter.text('limit: ' + maxLength + ' characters. remaining: ' + (maxLength - charCount));
            });
        });
    };

})(jQuery);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
    <textarea id="short-message" class="wordcount" maxlength="100" cols="8"></textarea>
    <p class="limit">limit: 100 characters</p>
</div>

<div class="form-group">
    <textarea id="short-shory" class="wordcount" maxlength="150" cols="8"></textarea>
    <p class="limit">limit: 150 characters</p>
</div>

<div class="form-group">
    <input id="nickname" class="wordcount" maxlength="50" size="32"/>
    <p class="limit">limit: 50 characters</p>
</div>
<script>
    $(document)
        .ready(function() {
            'use strict';
            $('.wordcount').characterCounter();
        });

</script>
&#13;
&#13;
&#13;

请检查,你有一个jquery依赖所以你需要为此添加jquery。 我使用 Common Class 以便它适用于所有类型的输入字段。

谢谢