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

JS代码中confirm确认框取消按钮失效仍跳转页面问题

问题原因
  • 核心逻辑错误:window.confirm() 执行后会返回布尔类型结果,点击「确认」返回 true,点击「取消」返回 false。原代码没有对这个返回值做任何判断,弹窗弹出后无论用户选什么,都会直接执行后续的跳转语句,所以点取消也会触发跳转。
  • 语法结构错误:HTML标签嵌套不合法,</center> 闭合标签被错误放在 </form> 之前,可能导致页面解析异常。
  • 细节问题:跳转URL字符串前多了一个多余空格,可能在部分浏览器下引发地址解析错误。
修复后完整代码
<html>
    <head>
        <title>password</title>
    </head>
    <body>
        <script type="text/javascript">
            function f() {
                if (myform.password.value == "") {
                    alert("you need to enter your password");
                    return;
                }
                // 仅用户点击确认时才执行跳转
                if (confirm("are you sure u want to proceed")) {
                    window.location.href = './target.html';
                }
            }
        </script>
        <center>
            <h1>confirm password page</h1>
            <form id="myform">
                Enter the Password
                <input type="password" id="password" value="">
                <input type="button" id="continue" value="continue" onclick="f()">
            </form>
        </center>
    </body>
</html>
关键修改点
  • 给confirm调用加了返回值判断,只有用户点击确认后才会执行跳转逻辑
  • 调整了</center>和</form>的闭合顺序,修复HTML嵌套不合法的问题
  • 去掉了跳转地址前的多余空格,改用更规范的window.location.href属性做跳转
  • 密码为空的分支增加return终止逻辑,代码可读性更高
  • 原代码中的外部跳转地址替换为站内相对路径示例,使用时替换成自己的实际目标地址即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 03:45:38