繁体   English   中英

按Enter键后如何调用onclick功能

[英]How to call the onclick function after pressing Enter

我正在制作聊天网络应用程序,发送消息, input type="text"input type="button" ,使用JavaScript中的函数,我设法通过添加onclick="sendMessage()"来解决它onclick="sendMessage()"作为input button的属性,但我需要点击它,但我希望它像任何聊天信使或应用程序一样工作,客户端写下来并点击ENTER键,如果我使用<form onsubmit="sendMessage()"> ,这可能会有效<form onsubmit="sendMessage()">input type="submit"但页面将刷新,我该怎么做?

 <form onsubmit="sendMessage();return false">

这可以防止向服务器发送请求的默认操作。

您将不得不挂钩文本框的onkeypress / up / down事件。 这应该让你开始: 在JavaScript中输入按键事件

使用onkeydown()(或keyPress或keyUp,取决于语义)而不是单击 - 这将使您获得一个事件与您想要的event.keyCode - 13 - 您可以使用AJAX请求轻松提交(即XMLHttpRequest)

简单代码: - 原始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>

在这种情况下,您还需要将“发布”按钮从“发布”更改为服务器并执行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();"/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM