【问题标题】:Trigger onclick event using enter [duplicate]使用回车触发onclick事件[重复]
【发布时间】:2019-01-07 04:57:21
【问题描述】:

我正在建立一个网站,并且有一个输入允许用户编写一些文本并在谷歌上搜索它。我已经完成了所有工作,只是用户必须单击搜索按钮才能将其转到 google。

我希望能够按回车键进行搜索。有什么办法吗?

代码:

<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);">

【问题讨论】:

    标签: javascript html


    【解决方案1】:

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

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

    这应该可以完成工作。

    【讨论】:

      【解决方案2】:

      这里已经回答了这个问题:Trigger a button click with JavaScript on the Enter key in a text box

      或者,将此脚本标记添加到您的 html 代码中:

      <script>
      document.getElementById("google-search")
          .addEventListener("keyup", function(event) {
          event.preventDefault();
          if (event.keyCode === 13) {
              document.getElementById("search-img").click();
          }
      });
      </script>
      

      【讨论】:

      • 如果已经回答,为什么还要回答?
      • 以防万一。我不知道不应该这样做。
      【解决方案3】:

      可能是这样的:

      <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);" 
           onkeydown = "if(event.keyCode == 13){document.getElementById('google-search').click();}">

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-20
        • 2011-06-05
        • 2014-07-27
        • 2019-02-21
        • 1970-01-01
        • 1970-01-01
        • 2013-03-21
        • 2019-05-28
        相关资源
        最近更新 更多