简体   繁体   English

我想在 javascript/html 中制作随机数生成器

[英]I want to make Random number generator in javascript/html

So basically i want to do is accept two values所以基本上我想做的是接受两个值

var a,b;

and then put them in max and min for random number generator然后将它们放入随机数生成器的最大值和最小值

 let x = Math.floor((Math.random() * 10) + 1);
 document.getElementById("demo").innerHTML = x; 

How do I get the values 10 and 1 be var a and b;如何将值101设为var a and b;

<!DOCTYPE html>
<html> 
<head>
<title> TEST </title> 
<script type="text/javascript">
function random()
{
var a,b; 
a=parseInt(form.v1.value);
b=parseInt(form.v2.value);
}

I have made this code for accepting values now how to i input them into max and min for my random number generator我已经编写了这段代码来接受值,现在如何将它们输入随机数生成器的最大值和最小值

Here is an example of how you could do this.这是您如何执行此操作的示例。

For a real application though, it is important to validate the input of the user before using it in your code.但是对于真实的应用程序,在您的代码中使用之前验证用户的输入很重要。 For example you should check if the maximum is higher than the minimum, if no malicious code is inserted etc.例如,您应该检查最大值是否高于最小值,是否未插入恶意代码等。

 btn = document.getElementById("button"); btn.addEventListener("click", () => { minInput = document.getElementById("min"); maxInput = document.getElementById("max"); min = Number(minInput.value); max = Number(maxInput.value); randomNumber = document.getElementById("random-number"); randomNumber.textContent = Math.floor( Math.random() * (max - min + 1) + min ); });
 <body> <h1>Random number generator</h1> <div style="display: flex; flex-direction: column; max-width: 300px"> <label for="max">Type your minimum here</label> <input type="number" id="min" /> <label for="min">Type your maximum here</label> <input type="number" id="max" /> <button id="button">Generate random number</button> <h2 id="random-number" style="text-align: center">...</h2> </div> </body>

 let x = Math.floor((Math.random() * 10) + 1);

Basically this line create a random number between 1 and 10, ...基本上这一行创建一个 1 到 10 之间的随机数,...

Now let us define a function to make it simple现在让我们定义一个 function 来简化它

function randomGen(min, max){
   let result = Math.floor((Math.random() * max) + min);
   return result
}

To get the value of a and b获取a和b的值

To get the value of a and b you can use onclick event in a form that call your function要获得 a 和 b 的值,您可以在调用 function 的表单中使用 onclick 事件

<button onClick="yourFunction()"> Create random </button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM