jQuery keyup事件只触发一次

时间:2016-06-25 10:02:58

标签: javascript jquery html css

为什么这个jQuery事件只会触发一次?

$(document).on('keyup', '[data-behavior="oneliner-text-area"]', function (event) {
  var textLength = $(this).length;
  var textLengthLimit = 140;
  $('[data-behavior="oneliner-counter"]').html(textLengthLimit - textLength);
  if ((textLengthLimit - textLength) < 0) {
    $('[data-behavior="oneliner-counter').addClass('oneliner-count-warning');
  }
});

2 个答案:

答案 0 :(得分:2)

你没有计算文本字段的文本长度,你正在计算元素的数量,它总是为1,所以你总是得到139。

$(document).on('keyup', '[data-behavior="oneliner-text-area"]', function (event) {
  var textLength = $(this).val().length; // Here is a change
  var textLengthLimit = 140;
  $('[data-behavior="oneliner-counter"]').html(textLengthLimit - textLength);
  if ((textLengthLimit - textLength) < 0) {
    $('[data-behavior="oneliner-counter').addClass('oneliner-count-warning');
  }
});

答案 1 :(得分:2)

我想,这就是你要做的事情:

$(document).on('ready', function() {
  $doc = $(document);

  var textProps = {
    textLength: 0, // your text length,
    textLengthLimit: 140, // your text limit
    charsLeft: function() { // check how characters left
      return this.textLengthLimit - this.textLength;
    },
    isLengthValid: function() { // check if text is valid
      return this.textLengthLimit - this.textLength > 0;
    }
  };

  $('.txtLimit').text(textProps.charsLeft());

  $doc.on('keyup', '[data-behavior="oneliner-text-area"]', function(e) {
    var $self = $(this);

    textProps.textLength = $self.val().length;

    $('.txtLimit').text(textProps.charsLeft());

    var success = 'oneliner-count-success',
      warning = 'oneliner-count-warning';

    if (!textProps.isLengthValid()) {
      $self.removeClass(success).addClass(warning);
    } else {
      $self.removeClass(warning).addClass(success);
    }
  });
});
.oneliner-count-warning {
  color: red !important;
}

.oneliner-count-success {
  color: green !important;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
  <div class="form-group col-xs-8">
    <label for="myInp">Input with validation:</label>
    <input type="text" class="form-control" data-behavior="oneliner-text-area" id="myInp">
    <small>Characters left: <b class="txtLimit"></b></small>
  </div>
</div>