【问题标题】:Textarea not react on .change()?Textarea 对 .change() 没有反应?
【发布时间】:2012-11-22 18:26:36
【问题描述】:
$(document).ready(function(){
    var keyUpTime = 0;                  
    var t = 0;
    var executeAfterOneSecond = false;
    $('#source').keyup(function(){
        if(executeAfterOneSecond == false){
            executeAfterOneSecond = true;
            t = setTimeout(function(){
                executeAfterOneSecond = false;
                sendValue($('#source').val());                          
                }, 600);
            }                                   
        keyUpTime = $.now();
        setTimeout(function(){
            if($.now() - keyUpTime >= 200) {
                clearTimeout(t);
                executeAfterOneSecond = false;
                sendValue($('#source').val());          
                }           
            },200);
    });
});

<textarea id="source" name="text" wrap="soft" tabindex="0" dir="ltr" spellcheck="false" autocapitalize="off" autocomplete="off" autocorrect="off" style="box-sizing: border-box; overflow-y: hidden; overflow-x: auto; padding-right: 20px; " class="oggy-textarea">
                                </textarea>

好吧,我希望我的代码可以在 change(); [$('#source').change(function(){---});],不在 keyup() 上,但它没有。我尝试使用 bind() 但没有。怎么了?

【问题讨论】:

  • 你怎么知道它不起作用?你做了什么实验,你期望什么结果,实际发生了什么?
  • 我在我的答案中添加了一大堆编辑 - 你可能会发现它们很有帮助:)

标签: javascript asp.net jquery-ui


【解决方案1】:

Change 事件仅在 input 控件丢失 focus 时发生 - 因此它没有触发。

请参阅此处的注释:http://www.w3schools.com/jquery/event_change.asp

您必须使用keyUpkeyPresskeyDown

你也可以真正清理你的方法。像下面这样的东西可能更稳定。

这将在最后一次按键后 1 秒后调用 sendValue()。将你的 22 行减少到 6 行:)

下面是jsFiddle的示例代码

   $(document).ready(function(){

      $("#source").keyup(function(){
         clearTimeout(this.timer);
         this.timer = setTimeout(function() {sendValue($("#source").val());}, 1000);
      });

   });

【讨论】: