我試圖做一個簡單的字符計數器,它顯示用戶是否輸入最小數量的字符,然後才能按下輸入。字符計數器上奇怪的jQuery錯誤
$(document).ready(function(){
$('#notification').hide();
$('#press_enter_notification').hide();
var allow_enter = false;
var min = 4;
var max = 30;
var char_count = 0;
$("#form_textbox").keydown(function() {
$('#press_enter_notification').hide();
if(this.value.length < min) {
char_count = min - (this.value.length) -1;
//alert('Too short');
$('#notification').show("fast");
$('#notification').text(char_count + ' more characters to go');
allow_enter = false;
} else if(this.value.length >= max) {
char_count = (this.value.length) - max;
this.value = this.value.substring(0,max);
$('#notification').show("fast");
$('#notification').text(' no more characters remaining');
} else {
char_count = max - (this.value.length) -1;
$('#notification').show("fast");
$('#notification').text(char_count + ' characters remaining');
$('#press_enter_notification').show("fast");
allow_enter = true;
}
});
$("form").submit(function() {
if (allow_enter == false)
{
$('#press_enter_notification').show("fast").text('you cannot press enter yet');
return allow_enter;
}
});
});
它的工作原理,但它具有以下怪癖:
- 當你輸入的東西,並刪除所有文字,字符計數消息犯規dissapear,或當你刪除計數向後
- 它所說的3個字符,我必須在
if(this.value.length < min) { char_count = min - (this.value.length) -1;
加-1,否則它可以讓你輸入5個字符,然後再停止說3,2,1個字符。
如果你在瀏覽器或jsbin中試試這個,你會注意到它們。我怎樣才能構建這個排序呢?
謝謝。
該事件可能只會觸發一次,但由於他將檢查keyup的最終長度,因此它不會在此特定實例中破壞任何內容。 – Dormouse 2011-05-26 20:17:24
只有關鍵事件的許多問題之一。當有人粘貼一堆文本時會發生什麼? – 2011-05-26 20:25:02
他的allow_enter變量默認爲false,因此表單不會提交。我並不是在暗示你所說的是錯誤的(在按鍵時有很多事情需要考慮),但是當這些問題相當容易克服時,我認爲插件是必要的。可能比外部插件中的鞋蹄更容易。 – Dormouse 2011-05-26 20:28:28