我有一个 HTML 表单,我试图用它导航到另一个页面。我试图使用 window.location.replace
将输入的值附加到表单的末尾,如下所示:
Before: https://example.com/search
我已经尝试了几乎所有我能找到的技巧,但都没有成功。我可以通过将 window.location.replace
替换为 window.open
来让它工作,但我不想在新选项卡中打开它。我也试过 window.location.assign
但运气不好。我尝试在 Chrome 控制台中运行这两个函数,它们运行良好。我的代码如下。
function onenter() {
var term = document.getElementById("searchbox").value;
window.location.replace("/search/" + term);
}
<form method="GET" onsubmit="onenter();">
<input id="searchbox" name="term" type="text" autofocus>
<button id="searchenter" type="submit">Enter</button>
</form>
我做错了什么/遗漏了什么?
最佳答案
您的问题是表单提交会重新加载页面。使用 eventObject.preventDefault
:
function onenter(event) {
event.preventDefault();
var term = document.getElementById("searchbox").value;
window.location.replace("/search/" + term);
console.log(window.location);
}
<form method="GET" onsubmit="onenter(e);">
<input id="searchbox" name="term" type="text" autofocus>
<button id="searchenter" type="submit">Enter</button>
</form>
关于javascript - 将 location.replace 与表单中的数据一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55153771/