新手问题 rails_tutorial chapter 10 练习 7: 给输入框添加字数统计。遇到一个奇怪的 bug,求思路。

lithium4010 · 2013年12月31日 · 最后由 lithium4010 回复于 2014年01月02日 · 2459 次阅读

bug 描述:

正常一个微博 140 个字符。现在输入了 10 个字符,标志显示还可以输入 130 个。这时候按退格,标志显示 129 了。再按退格又显示 130,131,132......,139(这时框中没有文字了),140.

相反的操作也会有类似的问题,比如现在标志 130 个,之前按的是退格。这时候输入一个字符,标志显示 131。

就是在删除和输入交替的时候统计的字符数会出现错误。

我是在 app/assets/javascripts/micropost_form.js 里面加入了相应的方法。

$(function(){
  var $micropost_content = $("#micropost_content");
  $micropost_content.keypress(change_surplus).keypress();
});

var change_surplus = function() {
  var surplus = 140 - $("#micropost_content").val().length;
    // surplus = max_length - content_length
  var $text = $("#surplus_count");

  // change number text.
  $text.text(surplus);

  // change the color. 
  var red = $text.hasClass("surplus-nagative");
  if(red && surplus > 0){
    $text.removeClass("surplus-negative");
  }
  if(!red && surplus <= 0){ 
    $text.addClass("surplus-negative");
  } 
}

不知道是哪里出了问题。。。

再添加一个 keyup 事件监听就解决了问题,但是总觉得有点不妥,更好的做法是什么呢?

$(function(){
  var $micropost_content = $("#micropost_content");
  $micropost_content.keypress(change_surplus).keypress();
  $micropost_content.keyup(change_surplus);
});
...

http://api.jquery.com/keypress/

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser.

#1 楼 @reyesyang 根据软件的行为来看和这段描述不符啊,backspace 的时候是可以触发事件的。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号