簡體   English   中英

當我在前一行注釋掉警報時,為什么我的JavaScript不再清除輸入框的值?

[英]Why does my JavaScript no longer clear the value of an input box when I comment out an alert on the previous line?

我寫了一個js,它看起來像

$('#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('');
    }
});

這將刪除該輸入框的內容, 但是當我評論警報消息時 ,它不會。 你能解釋一下為什么嗎?

好的,弄清楚會發生什么。

在Firefox瀏覽器中,事件流程為:

  1. 用戶按ESC鍵。
  2. 調用keydown事件處理程序,將值更改為空字符串
  3. 當keyup事件發生時,文本框值被“重新計算”,從而產生先前的值。

換句話說,您無法在keydown事件期間直接更改該值。

一個簡單的解決方法是使用計時器,在毫秒后更改值:

$('#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);
    }
});

更新了小提琴

$('#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
    }
});

現場演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM