如何在js中动态计算字符串长度?

时间:2015-04-15 06:48:33

标签: javascript asp.net-mvc

按照代码计算用户仍在写消息的消息数

<script>
 if (($('#Msg').val().length) <= 70) {
     $('#smscount').text(Math.ceil(($('#Msg').val().length) / 70));
 }
 else 
{
     $('#smscount').text(Math.ceil(($('#Msg').val().length) / 67));
}
</script>

但它保持除以70,当消息长度超过70个字符时,我需要将分隔符更改为67,我的意思是在我的情况下,else语句中的代码无法访问,为什么?

2 个答案:

答案 0 :(得分:1)

假设您要处理文本框的keyup事件,以便在您键入时更新值,那么脚本应为

var count = $('#smscount'); // cache it
$('#Msg').keyup(function() {
  var l = $(this).val().length;
  if(l <= 70) {
    count.text(Math.ceil(l / 70));
  } else {
    count.text(Math.ceil(l / 67));
  }
});

或者,您可以只处理.change().blur()事件,以便在文本框失去焦点时更新值。

答案 1 :(得分:0)

你必须动态调用javascript函数来获得msg的长度,如下所示:

       <input type="text" id="Msg" onChange="checkLength();" value=""></input>

       <div id="smscount"></div>

您必须在函数中添加javascript代码

       function checkLength(){

        if (($('#Msg').val().length) <= 70) {

          $('#smscount').text(Math.ceil(($('#Msg').val().length) / 67));
        }
        else 
         {
            $('#smscount').text(Math.ceil(($('#Msg').val().length) / 67));
         }
      }