javascript - 如何使用密码生成器的 if 语句从用户获取点击功能的价值?
问题描述
我对 JavaScript 很陌生,所以如果代码错误,请原谅我。当值是数字或字母时,我无法从用户那里获取值。
如果它是一个数字,函数应该执行,但如果它不是一个数字,它应该显示一个警告,告诉用户输入一个有效的数字。
好吧,当用户输入同时是字母和/或数字时,我的应用程序会显示警报。任何帮助将不胜感激。
我尝试使用 if 语句,该语句将显示在下面的 Generate click 函数下的代码中。编辑以包含 HTML。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Password Generator</title>
<link rel="stylesheet" href="password.css">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="password.js"></script>
</head>
<body>
<main>
<h1>Password Generator</h1>
<h2>Generate a strong password</h2>
<label for="num">Number of characters:</label>
<input type="text" id="num"><br>
<label for="password">Password:</label>
<input type="text" id="password" disabled><br>
<label> </label>
<input type="button" id="generate" value="Get Password">
<input type="button" id="clear" value="Clear"><br>
</main>
</body>
</html>
"use strict";
$(document).ready(function() {
var getRandomNumber = function(max) {
for (var x = 0; x < length; x++) {
var random;
if (!isNaN(max)) {
random = Math.random(); //value >= 0.0 and < 1.0
random = Math.floor(random * max); //value is an integer between 0 and max - 1
random = random + 1; //value is an integer between 1 and max
}
}
return random;
};
$("#generate").click(function() {
$("#password").val(""); // clear previous entry
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-+!@";
var num;
if (num >= 0 && num <= 100) {
//If the user entry is valid, the function will execute and return password
return num;
//If user entry isn't a valid number, display alert
} else if (isNaN(num)) {
alert(" Please enter a valid number ");
}
}); // end click()
$("#clear").click(function() {
$("#num").val("");
$("#password").val("");
$("#num").focus();
}); // end click()
// set focus on initial load
$("#num").focus();
}); // end ready()
解决方案
请提供html部分。
当您单击#generate 时,您没有定义 num 变量的值。
更改此行并重试
var num= $("#num").val();
推荐阅读
- xslt - xsl:如何混合身份转换和自定义规则?
- pyxb - 如何使用 PyXB 从生成的类中访问元素值
- webpack - Webpack 输出到 es5 / es6?
- xamarin.forms - mobileserviceclient loginasync“解析值时遇到意外字符:<.Path”
- json - MVC Newtonsoft JSON CustomJsonConverter
- android - fusedLocationProviderClient.lastLocation.addOnSuccessListener 始终为空
- c++ - “彩色游戏” - 从数组 C++ 中调用随机数
- tensorflow-hub - 如何使用 TF Hub 模块找到最接近的单词?
- rest - RESTful 中的“ful”是什么意思?
- xml - 未在 XSLT 中引用默认命名空间