2013-11-04 22 views
0

您好我在JavaScript中寫入字符計數器..like這的Javascript字符計數器,計馬車reurn爲2個字符

<textarea class="SmsText" id="txttemplate" maxlength="160" /> 
<span id="charsCount">160</span></strong><span>character(s) left</span> 
$(document).ready(function() { 
     keypressed = false; 
     $('#txttemplate').keypress(function (e) { 
      keypressed = true; 
     }); 

     $('#txttemplate').keyup(function() { 
      counter($(this)); 
     }); 

     $('#txttemplate').keydown(function() { 
      counter($(this)); 
     }); 

    }); 
function counter(obj) { 
     var max = obj.attr('maxlength'); 
     var valLen = obj.val().length; 
     obj.val(obj.val().substring(0, max)); 
     $('#charsCount').text(max - valLen); 
    } 

現在,我的代碼認爲「ENTER」鍵13爲單個字符,但最大長度textarea的屬性計爲2.根據我的代碼,如何在「enter」或「回車被按下」時計數兩個字符。

回答

2

您可以檢查按下的鍵事件參數,並相應地增加您的櫃檯

$('#txttemplate').live("keypress", function (e) { 
    if (e.keyCode == 13) { 
     //do increment here 
    } 
}