簡體   English   中英

如何為輸入添加回車鍵?

[英]How to add an enter press for an input?

我正在用一個輸入和一個按鈕創建一個“算命先生”function。 用戶寫一個問題,然后可以單擊 function 的按鈕完成。 然而,當用戶點擊回車時,什么也沒有發生。 我嘗試了一些在這里找到的解決方案,但沒有任何效果。 我不做很多JavaScript。 謝謝!

 var outcomes = [ "It is certain", "It is decidedly so", "Without a doubt", "Yes - definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "No", "My reply is no", "My sources say yes", "Outlook is not so good", "Yes", "Yes, it would benefit you", "Reply hazy, try again", "Very doubtful", "Signs point to yes", "No, it wouldn't benefit you" ]; function ask() { var x = document.getElementById("input-box").value; var sel = Math.floor(Math.random() * outcomes.length); var b8 = outcomes[sel]; if (x.indexOf('?') + 1) { document.getElementById("answer").innerHTML = b8; } else { document.getElementById("answer").innerHTML = "Try with a question mark (?)"; } }
 <div class="ask"> <input id="input-box"> <div class="button" onclick="ask()"> <img src="img/ask-1.png" onmouseover="this.src='img/ask-2.png';" onmouseout="this.src='img/ask-1.png';"> </div> <p id="answer"></p> </div>

您可以將keyup事件偵聽器添加到您的輸入中。 它應該如下所示:

<!-- rest of your code -->

<input id="input-box" />

<script>
document.getElementById("input-box").addEventListener("keyup", function(event) {
   // 13 in the code of the enter key
   if(event.keyCode == 13){
      // your function
   }
})
</script>

<!-- rest of your code -->

如果您將其放入表單並將return false添加到onsubmit (因此表單不會重定向)。 它應該工作。

代碼:

<div class="ask">
  <form onsubmit="ask(); return false;">
    <input id="input-box">
    <div class="button" onclick="ask()">
      <img src="img/ask-1.png" onmouseover="this.src='img/ask-2.png';" onmouseout="this.src='img/ask-1.png';">
    </div>
  </form>
  <p id="answer"></p>
</div>

暫無
暫無

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

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