我無法弄清楚爲什麼我的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