2017-05-27 49 views
3

我想問一問爲什麼會有多重響應?我怎樣才能輸入輸入字段只有一個響應?javascript keypress多記錄問題

期望:在輸入字段中輸入數據並按下回車鍵,它將執行操作。

$("#textInput").keypress(function (e) { 
 

 
    console.log("123"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 

 
<input type='text' id='textInput'/>

+0

[jQuery keypress事件在持有密鑰時會重複觸發 - 但不會在所有密鑰上觸發](https:// stackoverflow。com/questions/9098168/jquery-keypress-event-fires-repeated-when-key-is-held-but-not-all-keys) –

+3

我不同意重複的建議。 –

回答

0

的按鍵事件被髮送到當瀏覽器登記鍵盤輸入的元件。

- jQuery文檔link

你真正想要的是.submit(),因爲它們是在用戶提交的信息將只觸發了一個。

$("#textInput").submit(function (e) { 

console.log("123"); 
)}; 

或者,如果你只是想檢測輸入按鍵但不提交,使用此:
How to detect pressing Enter on keyboard using jQuery?

3

你在你的代碼有語法錯誤。收盤應該});而不是)};

$("#textInput").keypress(function (e) { 
 
    if(e.which == 13) { 
 
     alert('You pressed enter!'); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="textInput">

0

我想,你應該選擇其他的事件,像onblur解決您的問題

$("#textInput").on('blur',function (e) { 

    console.log("123"); 
)}; 

在你的代碼,keypress事件給你在每個按鍵動作中輸出,所以這就是你得到多個響應的原因

而接下來,如果你認爲,如果你想按Enter按鈕,然後需要響應,在這種情況下,小的變化將幫助你

$("#textInput").keypress(function (e) { 
    if(e.which == 13) { 
     console.log("123"); 
    } 


}); 
0

後市展望:輸入數據輸入字段,然後按回車它會執行這些操作。

爲了儘快提交相應形式的用戶輸入的文本字符串和最終回車鍵,你可以:

  • 測試,如果當前字符是回車鍵(e.which == 13)
  • 得到closest形式
  • submit形式

$("#textInput").on('keypress', function (e) { 
 
    if (e.which == 13) { 
 
     $(this).closest('form').submit(); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<form action="/action_page.php"> 
 
    Enter text and type enter to submit:<br> 
 
    <input type="text" name="textInput" value=""> 
 
</form>