javascript - 使用 location.replace 与表单中的数据
问题描述
我有一个 HTML 表单,我试图用它来导航到不同的页面。我试图使用window.location.replace
将输入的值附加到表单的末尾,如下所示:
我几乎尝试了我能找到的所有技巧,但没有运气。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>