Script works in Firefox, but in Safari and Chrome console it doesn't and shows error "Cannot access to uninitialized variable" in passLeft.textContent = "" line. Script is generating the password after pressing button in html script. I need this line to reset the output field every time after the button is pressed.
const characters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9","~","`","!","@","#","$","%","^","&","*","(",")","_","-","+","=","{","[","}","]",",","|",":",";","<",">",".","?",
"/"];
let passLeft = document.getElementById("outputLeft")
let passRight = document.getElementById("outputRight")
passLeft.textContent = "*****"
passRight.textContent = "*****"
function generatePassword() {
passLeft.textContent = ""
passRight.textContent = ""
for (let i = 0; i < 16; i++) {
let l = Math.floor(Math.random() * characters.length) // calls random array cell
passLeft.textContent += characters[l]
}
for (let i = 0; i < 16; i++) {
let l = Math.floor(Math.random() * characters.length) // calls random array cell
passRight.textContent += characters[l]
}
}
无论我在passLeft.textContent =“”行中输入什么值,按下按钮后,错误都是一样的:“无法访问未初始化的变量”。该错误发生在Safari和Chrome中,但在Firefox中一切正常。
这是我的HTML文件:
<head><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Karla:wght@200;400;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1>Generate a <div class="rnd">random password</div></h1>
<p> Never use insecure password again.</p>
<button onclick="generatePassword()">Generate passwords</button>
<hr>
<div class="container">
<div id="outputLeft" class="output"></div>
<div id="outputRight" class="output"></div>
</div>
<script src="index.js"></script>
</body>
2条答案
按热度按时间nwwlzxa71#
我试过你下面的代码,似乎工作正常。当得到HTML元素时,请确保你拼写正确的
ID
标签,否则它存在于你的HTML文档中。您可以运行下面的代码进行测试。
第一个
以上是我的HTML元素
8hhllhi22#
实际上,这是U+00 a0在index.js中数组括号[ ]之前的不可见字符,我删除了它并用空格替换。现在一切都正常了!