jQuery 字符计数器问题
发现这个非常简单的代码来显示我的文本输入的字符数:
http://www.jamesfairhurst .co.uk/posts/view/jquery_word_character_counter
我将其修改如下。但是,退格时它无法正常工作。它不能正确显示字符数。有人可以帮忙解决这个问题吗?
$(document).ready(function() {
$('.word_count').each(function() {
$(this).parent().find('.counter').html('Only ' + $(this).attr("size") + ' characters allowed');
// bind on key up event
$(this).keydown(function(event) {
k = event.keyCode;
// eat backspaces, tabs, and CRs
if(($(this).attr("size") - $(this).val().length) == 0&&(k!=8&&k!=9&&k!=13)) {
event.preventDefault();
} else {
if($(this).val().length==0) {
$(this).parent().find('.counter').html('Only ' + $(this).attr("size") + ' characters allowed');
} else {
$(this).parent().find('.counter').html(($(this).attr("size") - $(this).val().length-1) + ' characters left');
}
}
});
});
});
Found this very simple code to show character counts for my text inputs:
http://www.jamesfairhurst.co.uk/posts/view/jquery_word_character_counter
I modified it like below. However it isn't working correctly when backspacing. it doesn't display the char count correctly. Can somebody help fix this?
$(document).ready(function() {
$('.word_count').each(function() {
$(this).parent().find('.counter').html('Only ' + $(this).attr("size") + ' characters allowed');
// bind on key up event
$(this).keydown(function(event) {
k = event.keyCode;
// eat backspaces, tabs, and CRs
if(($(this).attr("size") - $(this).val().length) == 0&&(k!=8&&k!=9&&k!=13)) {
event.preventDefault();
} else {
if($(this).val().length==0) {
$(this).parent().find('.counter').html('Only ' + $(this).attr("size") + ' characters allowed');
} else {
$(this).parent().find('.counter').html(($(this).attr("size") - $(this).val().length-1) + ' characters left');
}
}
});
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该脚本有很多可以改进的地方。您的问题的根源由注释描述:
接下来,它使用
keydown
事件,因此它可能存在某些其他问题。它还从size
属性而不是更正确的maxlength
属性获取计数。以下是我重写的方法:这是一个演示。
There are a lot of things that could be improved about that script. The source of your problem is described by the comment:
Next, it uses the
keydown
event, so it might have certain other problems. It also takes the count from thesize
attribute rather than the more correctmaxlength
attribute. Here's how I would rewrite it:Here's a demo.
这就是你所说的“过度编程”。请参阅:jsfiddle。
它的效果即使不是更好,也同样好(因为它实际上可以识别退格键)。
对于如此简单的事情,您所关心的只是字段中的
keyups
。当然,这会捕获诸如 Shift、CTRL、ALT 等内容,但因为您所做的只是计算字段的长度并更新跨度,这并不重要。 KISS 的完美案例。That's what you call "over-programmed". See: jsfiddle.
It works just as well if not better (in that it actually recognizes backspaces).
For something this simple, all you care about is
keyups
in the field. Sure, this catches things like Shift, CTRL, ALT, etc. but since all you're doing is just counting the length of the field and updating a span, it hardly matters. Perfect case of KISS.请参阅 http://jsfiddle.net/powtac/XHsz6/18/ 查看工作演示。
See http://jsfiddle.net/powtac/XHsz6/18/ for a working demo.