我无法弄清楚为什么我的JavaScript不能正常工作。它与j Query以及它应该选择所有的文本区域标签,然后为每个文本区域统计输入的字符数量,然后不允许用户在达到最大长度后再输入字符数量,还显示字符计数器在每个文本区域框下。 它所做的只是显示剩余的字符,但在按下每个键后不会递减,并且在达到最大长度时也不会停止。它也不会选择所有的文本区域,只需要找到它的第一个区域。使用jQuery的TextArea字符计数器
这里是我的TextAreaCounter.js
$(document).ready(function){
var $texts = $('textarea[maxlength]');
$texts.each(function){
$var $this = $(this),
max = $(this).attr('maxlength'),
textId = $(this)attr.('id'),
$parent = $this.parent(),
countId = textId+'-count';
$div = $('<div>Characters Remaining: </div>').addClass('count-down').insertAfter($this);
$input = $('<input></input>').attr({
type:"text",
readOnly: "readOnly",
value: max,
id: countId
}).css({
width: "25px"
marginTop: "5px"
marginBottom: "10px"
}).addClass('readOnly').appendTo($div);
$this.on({
keyup: function(){
val = $this.val(),
countVal = $('#'+countId).val(),
if(val.length > max){
$this.val(val.substr(0,max));
alert('Max length exceeded: ' +max);
return false;
}else{
$('#'+countId).val(max-val.length);
}
},
blur: function(){
val=$this.val();
if(val.length > max){
$this.val(val.substr(0,max));
alert('Max length exceeded: ' +max);
return false;
}else{
$('#'+countId).val(max-val.length);
}
}
});
});
});
当我加了一些警示,在这里的代码没有显示,它表明,它没有得到与keyup事件的this.on部分。 我将这个外部js文件包含到一个jsp文件中,该文件是我的页面制作的,并且有我的文本区域。 我还为textarea元素添加了一个id和maxlength属性。 任何帮助将是伟大的谢谢你。
噢,抱歉,这只是在问题 – Sheldor 2012-08-07 04:53:09
注意一个错字是截断的字符串返回允许的最大长度为用户类型是非常笨重 - 更好的改变背景颜色或以其他方式将其突出显示为错误并将其留给用户修复。否则当用户尝试编辑字段的开始或中间时,用户会感到困惑,并开始删除_end _...中的多余字符。 – nnnnnn 2012-08-07 04:56:47