点击后按钮消失:密码生成器按钮无法重复生成密码
问题解决:密码生成后按钮消失的修复
核心原因
你用了document.write()输出密码,这个方法在页面加载完成后调用时,会清空整个页面现有内容重新写入,所以原来的按钮被覆盖消失了。
修复步骤
- 在页面中添加专门显示密码的容器,避免直接覆盖整个文档
- 替换
document.write()为修改容器内容的代码 - 修正随机数函数的bug:原函数可能返回超出数组索引的值,改用合法的随机索引生成方式
- 把随机数字
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
相关产品推荐
相关产品推荐

