长时间单击退格按钮,然后字数不会刷新

时间:2018-07-19 14:04:37

标签: javascript jquery

$("#desc_user").on('keyup', function() {
  var words = this.value.match(/\S+/g).length;
  if (words > 50) {
    var trimmed = $(this).val().split(/\s+/, 50).join(" ");
    $(this).val(trimmed + " ");
  } else {
    $('#word_left').text(50 - words);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea autocomplete="off" class="form-control input-sm description_notes errorAddDesc" type="text" placeholder="Please enter your text" id="desc_user" name="desc_user"></textarea><br>
<span id="word_left">50</span>

按下键后,下面是我的字数统计网址。

当我们按下长退格按钮尝试获取字数时,它不起作用,但是当我按下长退格按钮时,它并没有刷新。

jsfiddle

before long press backspace after long press backspace goes to 48 instead of 50

1 个答案:

答案 0 :(得分:1)

在计算单词数之前检查textarea是否有价值,这是解决您的问题的方法。

$("#desc_user").on('keyup', function() {
  var words;
  if (this.value)
    words = this.value.match(/\S+/g).length;
  else
    words = 0;

  if (words > 50) {

    // Split the string on first 50 words and rejoin on spaces
    var trimmed = $(this).val().split(/\s+/, 50).join(" ");
    // Add a space at the end to keep new typing making new words
    $(this).val(trimmed + " ");

  } else {
    $('#word_left').text(50 - words);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea autocomplete="off" class="form-control input-sm description_notes errorAddDesc" type="text" placeholder="Please enter your text" id="desc_user" name="desc_user"></textarea><br>
<span id="word_left">50</span>