首页 > 解决方案 > 使用 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);">

标签: javascripthtml

解决方案


您可能想要启动一个 keydown 事件侦听器。每当按下某个键时,都会触发此事件。其中一个参数是keyCode。当按下的键的键码等于回车键的键码时,触发其余的代码。

document.addEventListener("keydown", (e) => {
    if(e.keyCode === 13){
        "execute some code"
    }
});

这应该可以完成这项工作。


推荐阅读