You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML表单点击跳转按钮仅清空表单无跳转问题求助

问题根源

form标签内的button默认是submit类型,点击后会触发表单的默认提交行为(刷新当前页面、清空表单内容),该行为优先级高于你绑定的点击跳转事件,所以跳转逻辑没有被执行。另外你原来的代码末尾多了一个冗余的</form>闭合标签,也建议一并删除避免语法异常。

解决方案

你可以任选以下任意一种方法修复:

方案1:给button指定type为button

显式声明按钮类型是普通按钮,取消默认的提交行为:

<form>
    <input type="url" id="link" placeholder="Enter link of website:" required>
    <br>
    <button class="outline" id="open" type="button">Create gate</button>
</form>
<script type="text/javascript">
    document.getElementById("open").onclick = () => 
    location.assign(document.getElementById("link").value);
</script>

方案2:阻止表单的默认提交行为

给表单绑定submit事件,阻止默认行为后执行跳转,该方案可以复用input的required校验逻辑,输入不合法的链接格式时不会触发跳转,更符合使用需求:

<form id="linkForm">
    <input type="url" id="link" placeholder="Enter link of website:" required>
    <br>
    <button class="outline" id="open">Create gate</button>
</form>
<script type="text/javascript">
    document.getElementById("linkForm").onsubmit = (e) => {
        e.preventDefault();
        location.assign(document.getElementById("link").value);
    }
</script>

方案3:直接移除外层form标签

如果你的页面不需要用到表单的校验、提交等特性,直接去掉form标签即可解决问题:

<input type="url" id="link" placeholder="Enter link of website:" required>
<br>
<button class="outline" id="open">Create gate</button>
<script type="text/javascript">
    document.getElementById("open").onclick = () => 
    location.assign(document.getElementById("link").value);
</script>

内容的提问来源于stack exchange,提问作者Roho Carro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 07:09:01