为了账号安全,请及时绑定邮箱和手机立即绑定

如何为输入添加回车键?

如何为输入添加回车键?

白板的微信 2022-12-09 19:11:07
我正在创建一个带有一个输入和一个按钮的“算命先生”功能。用户写下一个问题,然后可以单击该功能的按钮来完成。然而,当用户点击回车时什么也没有发生。我尝试了在这里找到的一些解决方案,但没有任何效果。我没有做很多 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>
查看完整描述

2 回答

?
慕婉清6462132

TA贡献1804条经验 获得超2个赞

您可以将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 -->


查看完整回答
反对 回复 2022-12-09
?
HUH函数

TA贡献1836条经验 获得超4个赞

如果你把它放在一个表单中并添加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>


查看完整回答
反对 回复 2022-12-09
  • 2 回答
  • 0 关注
  • 128 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号