jQuery代码:
$(document).ready(function() {
$('.counter').each(function(index) {
$('.counter p span').html('0'); // set character length to 0
$('input', this).keyup(function() {
var CounterDiv = $(this).parent(); //
var Limit = $('p', CounterDiv).html().split(' / ')[1];
var CurrentLength = $(this).val().length;
if (CurrentLength == Limit) {
$('p span', CounterDiv).html(CurrentLength);
return false;
} else if (CurrentLength > Limit) {
var str = $(this).val();
$(this).val(str.substring(0, str.length - 1));
return false;
} else {
$('p span', CounterDiv).html(CurrentLength);
}
});
});
});
您有什么建议我该如何改进?我对语法不是100%肯定。
答案 0 :(得分:3)
使用原生html maxlength
属性作为输入
以下是示例:http://jsfiddle.net/8YdCh/16/
<强> HTML 强>
<input name="input1" type="text" maxlength="8" />
<强> JS 强>
$(document).ready(function() {
$('.counter').each(function(index) {
$('.counter p span').html('0'); // set character length to 0
$('input', this).keyup(function() {
var $countSpan = $(this).parent().find('.var-count'); // find the count span
var countValue = $(this).val().length + " / " + $(this).attr('maxlength'); // format value for count span 'current value lenght / maxlength attribute'
$countSpan.text(countValue); // set formatted value to your column span
});
});
});