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

使用onclick与window.open时表单验证失效,JS函数完全无法执行

问题排查与修复方案

嘿,我帮你梳理了下代码里的问题,这就是为啥你的函数完全失效的原因:

  • 方法调用错误:GetElementById 必须通过 document 对象调用,正确写法是 document.getElementById() —— 少了这个前缀的话,浏览器根本找不到这个方法,函数直接就报错中断了,后面的alert和window.open自然都跑不起来。
  • 没获取输入框的实际值:就算你拿到了输入框的DOM元素,变量a和b现在是元素对象,不是用户输入的文本内容,得用 .value 属性来获取输入值,比如 a.value。

下面是修正后的完整代码:

<html>
<head>
    <title> Validation </title>
    <script type="text/javascript" language="javascript">
        function myfunction() {
            var a = document.getElementById("log");
            var b = document.getElementById("pwd");
            // 这里要判断输入值,所以用a.value和b.value
            if (a.value === "log" && b.value === "pwd") {
                window.open("https://www.google.com");
            } else {
                alert("Your username or password is incorrect!");
            }
        }
    </script>
</head>
<body>
    <!-- 别忘了添加表单和按钮,绑定函数 -->
    <input type="text" id="log" placeholder="Username">
    <input type="password" id="pwd" placeholder="Password">
    <button onclick="myfunction()">Submit</button>
</body>
</html>

另外补充一点:如果是用表单的onsubmit事件触发函数,记得要在函数末尾加return false,不然页面会自动刷新,导致弹窗和新窗口的行为被打断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:38:23