首页 > 解决方案 > 如何将 onclick 功能添加到我的搜索栏

问题描述

我从这个站点获得了一个搜索栏的简单代码,我想向它添加一个功能,以便当用户单击搜索栏上的搜索图标时,它会将他们重定向到一个 URL。这是代码

<svg xmlns="http://www.w3.org/2000/svg" style="display:none">
      <symbol xmlns="http://www.w3.org/2000/svg" id="sbx-icon-search-13" viewBox="0 0 40 40">
    <path d="M26.804 29.01c-2.832 2.34-6.465 3.746-10.426 3.746C7.333 32.756 0 25.424 0 16.378 0 7.333 7.333 0 16.378 0c9.046 0 16.378 7.333 16.378 16.378 0 3.96-1.406 7.594-3.746 10.426l10.534 10.534c.607.607.61 1.59-.004 2.202-.61.61-1.597.61-2.202.004L26.804 29.01zm-10.426.627c7.323 0 13.26-5.936 13.26-13.26 0-7.32-5.937-13.257-13.26-13.257C9.056 3.12 3.12 9.056 3.12 16.378c0 7.323 5.936 13.26 13.258 13.26z"
    fill-rule="evenodd" />
      </symbol>
      <symbol xmlns="http://www.w3.org/2000/svg" id="sbx-icon-clear-3" viewBox="0 0 20 20">
    <path d="M8.114 10L.944 2.83 0 1.885 1.886 0l.943.943L10 8.113l7.17-7.17.944-.943L20 1.886l-.943.943-7.17 7.17 7.17 7.17.943.944L18.114 20l-.943-.943-7.17-7.17-7.17 7.17-.944.943L0 18.114l.943-.943L8.113 10z" fill-rule="evenodd" />
     </symbol>
    </svg>

    <form novalidate="novalidate" onsubmit="return false;" class="searchbox sbx-custom">
      <div role="search" class="sbx-custom__wrapper">
    <input type="search" name="search" placeholder="Search your website" autocomplete="off" required="required" class="sbx-custom__input">
    <button type="submit" title="Submit your search query." class="sbx-custom__submit">
      <svg role="img" aria-label="Search">
        <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sbx-icon-search-13"></use>
      </svg>
    </button>
        <button type="reset" title="Clear the search query." class="sbx-custom__reset">
      <svg role="img" aria-label="Reset">
        <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sbx-icon-clear-3"></use>
      </svg>
    </button>
      </div>
    </form>
    <script type="text/javascript">
      document.querySelector('.searchbox [type="reset"]').addEventListener('click', function() {  this.parentNode.querySelector('input').focus();});
</script>

我对JavaScript一无所知。有人可以告诉我如何做到这一点,最重要的是我将把代码放在哪里?

标签: javascript

解决方案


您可以在内部head或内部的任何位置添加 javascript 代码bodybody理想的方法是在标签结束之前添加 JS 代码,在所有其他 HTML 之后。

至于你想要的功能,你的代码

document.querySelector('.searchbox [type="reset"]').addEventListener('click', function() {  this.parentNode.querySelector('input').focus();});

单击按钮时清除搜索输入并聚焦于它reset

为了让您的提交按钮重定向到某个地方,我们需要更多信息,但总体思路是这样的:

document.querySelector('.searchbox button[type="submit"]').addEventListener('click', function() {  window.location.assign('your url here');});

这会将用户带到该网址,他们可以通过回击返回上一页。

如果您使用window.location.replace()它,它会做同样的事情,但旧页面的历史记录将被新 URL 替换。


推荐阅读