请告诉我如何添加字数限制而不是字符限制

时间:2015-07-30 07:10:02

标签: jquery



$('input[type="text"]').on('keyup', function() {

  var text = this.value.split(' ');
  if (text.length >= 2) {
    this.value = text[0] + ' ' + text[1];
    console.log('Word limit is 2.');
  }
});
  var text = $('.test').text().trim().split(' ');
  if (text.length >= 2) {
    $('.test').text(text[0] + ' ' + text[1]);
    console.log('Word limit is 2.');
  }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="test">Lorem Ipsum is simply dummy text of the printing</div>
<div class="test">Ipsum is simply dummy text of the printing</div>
<div class="test">is simply dummy text of the printing</div>
&#13;
&#13;
&#13;

请告诉我如何添加字数限制而不是字符限制。

喜欢这个

Lorem Ipsum只是打印的虚拟文本

结果:( Lorem Ipsum),(Ipsum是),(简直就是)

3 个答案:

答案 0 :(得分:0)

您可以尝试这样:

function wordslimit(str) {
  var count=0;
  for(i=0;i<str.trim().length;i++) {
    if(str[i]==' ') 
      count++;
  }
  if(count>1)
      alert('Not more than 2 words');
}

DEMO

答案 1 :(得分:0)

你在这个堆栈溢出问题和答案中找到了你的问题解决方案。找到jsfiddle demo

<强> Your question solution click here

答案 2 :(得分:0)

您可以这样做:

&#13;
&#13;
$('.test').text(function() {
  var text = $(this).text().trim().split(' ');
  if (text.length >= 2) {
    return text[0] + ' ' + text[1];
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">Lorem Ipsum is simply dummy text of the printing</div>
<div class="test">Ipsum is simply dummy text of the printing</div>
<div class="test">is simply dummy text of the printing</div>
&#13;
&#13;
&#13;