首页 > 解决方案 > 如何使网站进入正确的链接

问题描述

我想从输入文本中获取用户输入,所以我在 html 文件上制作了表单:

<form class="inputform">
  <input type="text" id="getinput" autocomplete="off">
  <button id="hrefbutton" type="submit" onclick="hrefinput()">Search</button>

我在 HTML 文件的头部写了 Javascript:

function hrefinput(){
  const inputs = document.getElementById('getinput').value;
  alert(inputs);
  window.location.href = "http://localhost/index/" + inputs;
}

而且,每次我测试这段代码时,我都会成功地通过我的输入获得警报,但该网站只会转到“ http://localhost/index/?”我已经搜索过这个,但我在我的互联网上找不到这类问题。有人帮助我如何成功进入“ https://localhost/index/<inputs>”。谢谢,

标签: javascripthtml

解决方案


欢迎来到 StackOverflow

您面临的问题是由于 HTML 表单默认行为,它通过导航到特定actionURL 来发送表单数据。由于您没有action在表单元素上指定属性,您的浏览器不知道在哪里导航。那显然把你送到了/?

那么如何避免这种默认行为呢?这很容易。您只需在事件上调用该preventDefault函数。submit只需确保将事件传递给您的hrefinput函数,如下所示:

<html>
<head>
</head>

<body>
  <form class="inputform" onsubmit="hrefinput(event)">
    <input type="text" id="getinput" autocomplete="off">
    <button id="hrefbutton" type="submit">Search</button>
  </form>

  <script>
  function hrefinput(event){
    event.preventDefault()
    const inputs = document.getElementById('getinput').value;
    alert(inputs);
    window.location.href = "http://localhost/index/" + inputs;
  }
  </script>
</body>
</html>

注意:

  • 我将您的功能从onclick按钮上移到了表单元素上,因为它更合适

推荐阅读