簡體   English   中英

如何使用if語句為密碼生成器從用戶的點擊功能中獲取價值?

[英]How can I get value from user for click function using if statement for a password generator?

我對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>&nbsp;</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();

您應該讓用戶輸入變量,並驗證

var num = $("#password").val(""); // clear previous entry        

if (isNaN(num)) {
  return alert(" Please enter a valid number ");
}
else {

  if (num >= 0 && num <= 100) {
     return num;
  else
     // ..... return another error message here

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM