javascript - 如何使网站进入正确的链接
问题描述
我想从输入文本中获取用户输入,所以我在 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>
”。谢谢,
解决方案
欢迎来到 StackOverflow
您面临的问题是由于 HTML 表单默认行为,它通过导航到特定action
URL 来发送表单数据。由于您没有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
按钮上移到了表单元素上,因为它更合适
推荐阅读
- xml - 动态地将孩子兄弟姐妹的价值观吸收到一个父母的文本中
- asp.net-core - SwaggerUI Asp.Net Core - 如何引用 .json 文件
- c++ - 线程池在一些循环后阻塞主线程
- java - 如何在自定义启动器中支持快捷方式固定?
- vb.net - 如何让我的 errProvider 正确显示?
- php - 使用外键 laravel 连接数据库表
- c++ - 并非本地主机上所有 udp 发送的数据包都显示在 wireshark 上
- getstream-io - 有没有办法在仪表板或 CLI 中查看/管理所有用户、频道?
- machine-learning - 制作 Nauto 手势检测模型
- java - (Javax swing) repaint() 有时不调用paintComponent()