【问题标题】:Is there any solution to resolve my input problem?有什么办法可以解决我的输入问题吗?
【发布时间】:2022-01-07 15:13:34
【问题描述】:

您好,我想解决这个问题,当我的输入不在我的表单中并且我按回车时,会执行 google 搜索,但是当它在它不起作用时,没有进行重定向

<form>
  <fieldset>
    <legend>Bonjour, ---.</legend>
    <div class="inner-form">
      <div class="input-field">
        <button class="btn-search" type="button">
          <i class="fab fa-google fa-1x"></i>
        </button>

        <input id="textbox" type="text"
          placeholder="Rechercher sur Google..."
          onkeydown="if (event.keyCode == 13 || event.which == 13) { location='http://www.google.com/search?q=' + encdeURIComponent(document.getElementById('textbox').value);}"
        />

      </div>
    </div>
    <style type="text/css">
      a:link {
        text-decoration: none
      }
    </style>
    <div class="suggestion-wrap">
      <a href="https://youtube.com"><span>YouTube</span></a>
      <a href="https://netflix.com"><span>Netflix</span></a>
      <a href="https://www.zara.com/fr/"><span>ZARA</span></a>
      <a href="https://www.apple.com/"><span>Apple</span></a>
    </div>
  </fieldset>
</form>

【问题讨论】:

  • 与其做一个keydown,为什么不使用它应该如何使用的表单并设置动作和方法属性——阅读这个:developer.mozilla.org/en-US/docs/Web/HTML/Element/form
  • 正如@Pete 所说,最好使用&lt;form&gt; 标签而不是keydown 事件。这将大大简化您的代码,并允许更轻松地识别问题。

标签: html input


【解决方案1】:

在表单中按回车键提交表单。您的表单没有 action 属性,因此提交表单只会重新加载页面。

您实际上不需要任何 javascript 来进行 google 搜索。只需将输入的名称设置为“q”,将表单的操作设置为“https://google.com/search”,然后让表单执行表单的用途。

<form action="https://google.com/search">
  <input type="text" name="q" placeholder="Rechercher sur Google..." />
</form>

如果出于某种原因,使用 javascript 而不是常规的表单提交很重要,则需要阻止 keydown 事件的默认操作,这样表单就不会提交:

if (event.keyCode == 13 || event.which == 13) {
   event.preventDefault(); // prevent form submission
   location='http://www.google.com/search?q=' + encdeURIComponent(document.getElementById('textbox').value);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 2023-01-26
    相关资源
    最近更新 更多