没有从textBox获取最新值

时间:2011-12-01 23:49:12

标签: javascript jquery textbox coffeescript

我正在尝试在coffeescript / jquery

中实现以下内容

- >当用户输入时,检查textBox是否为空(或者有“写评论...”文本),隐藏“添加评论”按钮。否则显示“添加评论”按钮

enter image description here

enter image description here

但是,我面临的问题是从文本框返回给我的val()始终是一个键击。

例如,如果我在框中输入'sad',则target.val()仅返回'sa'。

enter image description here

当我输入时,如何在文本框中获取最新值?

我的实施如下

events:
  "keydown .comment_area": "commenting"

commenting: (e) ->
  target = @$(e.currentTarget)

  //target.val() is not returning me the latest character entered in the box
  if $.trim(target.val()) == "" or $.trim(target.val()) =="Write a comment..."
    //hide the 'add' button
    @$('.add_comment').hide()
  else
    //show the 'add' button
    @$('.add_comment').show()

2 个答案:

答案 0 :(得分:5)

绑定到keyup事件而不是keydown

请参阅keyboard event order

答案 1 :(得分:0)

使用keyupkeypress事件:keydown在计算机实际将字符放入文本框之前触发,而其他两个事件在此之后触发:{{1}之后,当钥匙被物理抬起时,keypress。我认为,keyup会触发插入文本框的每个字符(即,当您按住并且字符重复时,它会单独触发),而keypress仅在键被提升后触发,因此如果您按住某个键,它只会在该键被提起后触发,而不是每个插入的字符都会被触发。

顺便说一下,在coffeescript中,只有当你没有传入任何参数时,函数调用才需要括号。例如:

keyup - > @$(e.currentTarget)

@$ e.currentTarget - > $.trim(target.val())

另外,我注意到有时你用$.trim target.val()引用$,而有时候你正在使用全局jQuery - 这有什么理由吗?它似乎应该是一致的。

相关问题