这是我写的一个快速简单的 jQuery 插件。您需要做的就是$("#element_id").jqCounter();
给输入或文本区域一个字符计数器。它响应粘贴、更改和我能想到的所有其他内容。
您必须设置 maxlength 属性才能使其工作,即。<input maxlength=45 />
或者<textarea maxlength=45></textarea>
<script>
(function($) {
$.fn.extend({
jqCounter : function(givenOptions) {
return this.each(function() {
var $this = $(this),
options = $.extend({
divider: "/" // The diveder character between the count and max
}, givenOptions);
// 0 chars or max count not set or already setup
if($this.attr("maxlength") <= 0 || $this.hasClass("jqCounter")) return;
// Add the counter text after the element
var span= $("<span style=\"font-size:10px;\">"+$this.val().length+options.divider+$this.attr("maxlength")+"</span>")
.insertAfter($this);
// Add a class
$this.addClass("jqCounter")
// React to keypresses, changes, paste, etc. and change the counter
.on('focus blur propertychange change input paste keydown keyup keypress', function(){
setTimeout(function(){
var maxChars = $this.attr("maxlength"),
txtLength = $this.val().length;
span.text( txtLength + options.divider + maxChars );
},
1);
});
});
}
});
})(jQuery);
$(document).ready(function()
{
// All text areas will have a content counter
$("textarea").jqCounter();
});
</script>