【问题标题】:Append input from search box into button link将搜索框中的输入附加到按钮链接中
【发布时间】:2020-10-02 12:39:55
【问题描述】:

我会让这个简短而快速。 :)

我正在尝试在我的网站上实现一个按钮,它将我重定向到我指定的 URL + 用户正在寻找的内容。

我这里有一小段代码:

<html>
  <div class="search">
    <form role="search" method="get" id="search">
        <div>
            <input type="text" value="" name="tag_search" id="tag_search" />
            <input type="button" value="Cerca" onclick="window.location.href='https://mywebsite.com/'" />
        </div>
    </form>
  </div>
</html>

几乎工作了。

唯一的问题是,如果用户在搜索框中输入“你好”,一旦你按下“提交”按钮,它将始终搜索以下 URL:https://mywebsite.com/

如何将用户写入的内容附加到搜索框中,以便按钮将我重定向到:https://mywebsite.com/Hello

谢谢大家!

【问题讨论】:

    标签: php html wordpress button hyperlink


    【解决方案1】:

    将输入的值添加到链接中

    <html>
      <div class="search">
        <form role="search" method="get" id="search">
          <div>
            <input type="text" value="" name="tag_search" id="tag_search" />
            <input type="button" value="Cerca" 
              onclick="window.location.href='https://mywebsite.com/' + 
              document.getElementById('tag_search').value" />
          </div>
        </form>
      </div>
    </html>

    【讨论】:

      【解决方案2】:

      添加以下 Javascript 来帮助

      <script>
      function goToSearch() {
          window.location.href= 'https://mywebsite.com/' + encodeURI(document.getElementById("tag_search").value)
      }
      
      </script>
      

      那么你的 HTML 应该是这样的

      <html>
        <div class="search">
          <form role="search" method="get" id="search">
              <div>
                  <input type="text" value="" name="tag_search" id="tag_search" />
                  <input type="button" value="Cerca" onclick="goToSearch()" />
              </div>
          </form>
        </div>
      </html>
      

      【讨论】:

      • @SlimShadys encodeURI() 对于确保生成的 URL 是网络安全的很重要。
      猜你喜欢
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多