我练的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 is not a function
我不知道为什么,有人可以帮我吗?
不知道,我有这个[的jsfiddle(https://jsfiddle.net/jsupv7qy/1/) – George
@George你的小提琴是使用jQuery 3.2.1,但OP具有工作过时的jQuery 1.10.2。在你的小提琴上更改为1.19或2.2也会产生错误 - 事实证明这是由负载顺序引起的 - 将文档移动到js并且它再次正常工作。 https://jsfiddle.net/jsupv7qy/2/ –
它看起来像是因为您的文档已准备好在脚本之前运行。 OP中的代码看起来像正确的顺序 - 你能确认你的实际代码是否也是这个顺序吗? –