我有一个我试图用来导航到其他页面的HTML表单。我试图使用window.location.replace
将输入的值附加到表单的末尾:
之前:https://example.com/search
之后:https://example.com/search/formvalue
我几乎尝试了我能找到的每个技巧,但没有运气。我能够通过用window.open
替换window.location.replace
来使其有效,但是我不想在新标签中打开它。我也尝试了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>