我正在尝试创建一个简单的JavaScript密码生成器,以吐出用户输入的字符数。因此,可以说您输入了数字7。我希望程序然后从可能性变量中吐出7个随机字符。下面是我到目前为止的代码:
var possibilities = ['A', 'B', 'C', 'D', 'E', 'F', '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
];
var special_chars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?"; //no special characters
function generator() {
if (document.getElementById("input").value == '' || document.getElementById("input").value > 61) {
alert("Enter under 61 characters");
} else if (isNaN(document.getElementById("input").value) || document.getElementById("input").value == special_chars) {
alert("Enter numbers only");
} else {
//var userInput = document.getElementById("input").value -- get value of this when clicked, spit out number of items from this array based on the value collected
for (var x = 0; x < possibilities.length; x++) {
var content = possibilities[Math.floor(Math.random() * possibilities.length)];
}
document.getElementById("random_password").innerHTML = content;
}
}
我对JavaScript有点陌生,有点卡在这里,所以不胜感激:)提前谢谢!
最佳答案
这是一个工作示例。这使用在here中找到的现有答案。我添加了一些细微的改动来适应这个问题。
function makeid(){
var IdLength=document.getElementById('IdLength');
//Strip anything but 0 to 9
var UserInput=IdLength.value.replace(/[^0-9.]/g, "");
//Update input value
IdLength.value=UserInput;
var Results=document.getElementById('results');
var text = "";
var shuffle = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
//Is input is empty?
if(IdLength!==''){
for( var i=0; i < IdLength.value; i++ ){
text += shuffle.charAt(Math.floor(Math.random() * shuffle.length));
}
Results.innerHTML=text;
}
}
<input type="text" id="IdLength" oninput="makeid()" placeholder="Enter 0-9"/>
<span id="results"></span>
我希望这有帮助。编码愉快!