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

点击后按钮消失:密码生成器按钮无法重复生成密码

问题解决:密码生成后按钮消失的修复

核心原因

你用了document.write()输出密码,这个方法在页面加载完成后调用时,会清空整个页面现有内容重新写入,所以原来的按钮被覆盖消失了。

修复步骤

  1. 在页面中添加专门显示密码的容器,避免直接覆盖整个文档
  2. 替换document.write()为修改容器内容的代码
  3. 修正随机数函数的bug:原函数可能返回超出数组索引的值,改用合法的随机索引生成方式
  4. 把随机数字num1移到生成函数内部,确保每次点击都生成新数字

修改后的完整代码

<!DOCTYPE html>
<html>
<head>
    <title> Password Generator </title>
</head>
<body>
    <button onclick="PasswordGen()">Generate Password</button>
    <!-- 添加显示密码的容器 -->
    <div id="passwordDisplay" style="margin-top: 10px;"></div>

    <script>
        const emotion = ["Sad", "Happy", "Mad", "Miserable", "Shy", "Cheerful", "Angry", "Amazing", "Anxious", "Scared", "Bashful", "Brave", "Tired", "Excited", "Cautious", "Bubbly"];
        const noun = ["Actors", "Queens", "Kings", "Princes", "Princesses", "Cows", "Pigs", "Chickens", "Dogs", "Cats", "Clouds", "Fathers", "Mothers", "Brothers", "Sisters", "Uncles", "Aunties", "Zebras", "Fish", "Elephants"];
        const verb = ["Jump", "Play", "Run", "Sprint", "Walk", "Throw", "Fall", "Fly", "Search", "Train", "Grow", "Smell",  "Eat", "Whistle", "Write", "Read", "Swim", "Win", "Plan", "Scream", "Sleep"];

        // 修正随机索引生成函数:返回0到数组长度-1的合法索引
        function RandomNum(array) {
            return Math.floor(Math.random() * array.length);
        }

        function PasswordGen() {
            // 每次点击都生成新的随机数字(1-9)
            const num1 = Math.floor(Math.random() * 9) + 1;
            const password = num1 + emotion[RandomNum(emotion)] + noun[RandomNum(noun)] + verb[RandomNum(verb)];
            // 修改容器内容,而非覆盖整个页面
            document.getElementById("passwordDisplay").textContent = password;
        }
    </script>
</body>
</html>

关键改动说明

  • 新增passwordDisplay容器:专门用来展示密码,和按钮互不干扰
  • 替换document.write():用textContent更新指定区域的内容,不会影响页面其他元素
  • 修正随机数函数:Math.floor(Math.random() * array.length)确保生成的索引始终在数组合法范围内,避免出现undefined
  • 移动num1到函数内:原来的写法只会在页面加载时生成一次数字,现在每次点击都会生成新的随机数,密码更随机

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:39:20