2012-02-01 21 views
0

我写了一个js和它看起来像为什么当我在上一行注释掉警报时,我的JavaScript不再清除输入框的值?

$('#searchform').keydown(function(event) { 
    if (event.which == '13') { 
     submitForm(); 
     return; 
    }else if (event.which == '27'){ 
     alert("ESC keydown TO DO - Clear the contents from search box "); 
     $('#id_search').val(''); 
    } 
}); 

这将删除输入框,的内容,但是当我发表评论警报消息,它不会。你能解释我为什么吗?

+1

这不应该发生。你如何评论这条线?你有什么错误吗? – 2012-02-01 09:59:15

+0

也许事件干扰某种方式?您可以尝试取消事件,和/或启动计时器并在10ms后清除框。 – Rup 2012-02-01 10:00:15

+0

@皮卡我评论out line by //这 – user1066679 2012-02-01 10:02:31

回答

2

行,想通了,会发生什么。

在Firefox浏览器中,事件的流程是:

  1. 用户按下ESC 关键
  2. ​​事件处理程序被调用,值被更改为空字符串
  3. 当发生按键事件时,文本框的值将被“重新计算”,从而产生前一个值。

换句话说,您不能直接更改​​事件期间的值。

一个简单的解决方法是使用定时器,毫秒之后改变值:

$('#searchform').keydown(function(event) { 
    if (event.which == '13') { 
     submitForm(); 
     return; 
    }else if (event.which == '27'){ 
     //alert("ESC keydown TO DO - Clear the contents from search box "); 
     window.setTimeout(function() { 
      $('#id_search').val(''); 
     }, 1); 
    } 
}); 

Updated fiddle

+0

工作像魔术。这次真是万分感谢。 但仍然在Firefox 3.6上出现错误。 无论如何感谢这 – user1066679 2012-02-08 07:30:57

+0

火狐3.6就像IE6可能更糟。 ** [升级](HTTP://www.mozilla。组织/ EN-US /火狐/全older.html)** – 2012-02-08 07:50:37

0
$('#searchform').keydown(function(event) { 
    if (event.which == '13') { 
     submitForm(); 
     return; 
    }else if (event.which == '27'){ 
     $('#id_search', this).val(''); // this line was your problem. `$('#id_search', this)` referred the input field with the form with which the event binded 
    } 
}); 

LIVE DEMO

+0

它不工作 – user1066679 2012-02-01 11:25:07

+0

@ user1066679请检查现场演示 – thecodeparadox 2012-02-01 11:36:25

相关问题