javascript - 使用 enter 触发 onclick 事件
问题描述
我正在建立一个网站,并且有一个输入允许用户编写一些文本并在谷歌上搜索它。我已经完成了所有工作,只是用户必须单击搜索按钮才能将其转到谷歌。
我希望能够按回车键并搜索。有什么办法吗?
代码:
<img id="google-logo" src="1280px-Google_2015_logo.svg.png">
<input placeholder="Pesquisar na Web" id="google-search">
<img src="search.png" id="search-img" value="Submit" onClick="javascript: window.location.replace('http://www.google.com/search?q=' + document.getElementById('google-search').value);">
解决方案
您可能想要启动一个 keydown 事件侦听器。每当按下某个键时,都会触发此事件。其中一个参数是keyCode。当按下的键的键码等于回车键的键码时,触发其余的代码。
document.addEventListener("keydown", (e) => {
if(e.keyCode === 13){
"execute some code"
}
});
这应该可以完成这项工作。
推荐阅读
- c# - 通过触摸按钮或图像而不是 A - D 键在表面上左右移动 3d 块
- powerbi - 在 Power BI 中显示为另一列的百分比
- python - 函数变量的范围
- javascript - 添加列表项的 URL 并将其添加为按钮的链接
- html - 垂直和水平居中对齐容器 div 内的图像和文本
- hibernate - 如何通过仅访问数据库一次来将对象列表存储在数据库中?
- swift - 当应用程序在 iOS12 中进入后台时,URLSessionDelegate 的 didWriteData 不会调用
- laravel - 不能使用多个项目
- ios - 未找到 GStreamer Xcode 10.1 gst/gst.h
- python - 为函数内的全局变量赋值