javascript 回车后如何调用onclick函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12100203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call the onclick function after pressing Enter
提问by Ali Bassam
I am making a chat web application, to send a message, there's an input type="text"
and an input type="button"
, using a function in JavaScript, I managed to work it out by adding onclick="sendMessage()"
as an attribute for the input button
, but I need to click on it, but I want it to work like any chat messengers or apps, the client writes something down and hits ENTER key, this could work if I used a <form onsubmit="sendMessage()">
and input type="submit"
but then the page will refresh, How can I do this?
我正在制作一个聊天 Web 应用程序,要发送消息,有一个input type="text"
和一个input type="button"
,使用 JavaScript 中的一个函数,我设法通过添加onclick="sendMessage()"
作为 的属性来解决它input button
,但我需要单击它,但我想要它要像任何聊天信使或应用程序一样工作,客户端会写下一些东西并按 ENTER 键,如果我使用 a 这可以工作<form onsubmit="sendMessage()">
,input type="submit"
但随后页面将刷新,我该怎么做?
采纳答案by Snowball
<form onsubmit="sendMessage();return false">
That prevents the default action of sending a request to the server.
这可以防止向服务器发送请求的默认操作。
回答by njoshsn
This in-case you want also diable the enter button from Posting to server and execute the Js script.
以防万一您还想禁用从 Posting to server 的 enter 按钮并执行 Js 脚本。
<input type="text" id="txtSearch" onkeydown="if (event.keyCode == 13)
{document.getElementById('btnSearch').click(); return false;}"/>
<input type="button" id="btnSearch" value="Search" onclick="doSomething();"/>
回答by Michael Evangelist
You'll have to hook into the onkeypress/up/down events for the textbox. This should get you started: Enter key press event in JavaScript
您必须挂钩文本框的 onkeypress/up/down 事件。这应该会让你开始: 在 JavaScript 中输入按键事件
回答by Technologeeks
Use onkeydown() (or keyPress or keyUp, depending on semantics) instead of on click - this will get you an event with the event.keyCode you want - 13 - and you can easily submit using an AJAX request (i.e. XMLHttpRequest)
使用 onkeydown()(或 keyPress 或 keyUp,取决于语义)而不是单击 - 这将为您提供一个带有您想要的 event.keyCode 的事件 - 13 - 您可以使用 AJAX 请求(即 XMLHttpRequest)轻松提交
Simple Code: - raw Javascript, Don't need JQuery:
简单代码: - 原始 Javascript,不需要 JQuery:
<html>
<script>
function keyPress(e)
{
if (!e) e = window.event; // needed for cross browser compatibility
alert(e.keyCode); // You want 13 here , so
// if (e.keyCode == 13)
// etc..
// return true; or false, if you want to cancel event
}
</script>
<body>
<input type="text" onkeydown="keyPress()" size="20"/>xx
</body>
</html>