[英]hello, I would like to have a different random number, but I always get the same, an idea?
I want to have a random number different when I "click" on my button #roll, but I always get the same number.当我“单击”按钮#roll 时,我希望有一个不同的随机数,但我总是得到相同的数字。 someone could help me please?
有人可以帮我吗?
this is my code:这是我的代码:
//création nombre aléatoire function getRandomInt(min, max) { return Math.floor(Math.random() * (max, min + 1)+ min); } numberRandom = getRandomInt(1, 7) //création du lancé de dé const roll = document.getElementById("roll") roll.addEventListener('click',()=>{ alert(numberRandom) })
<button class="favorite styled" type="button" id="roll"> Lancer le dé </button>
Your problem is that numberRandom = getRandomInt(1, 7)
is run once when the page is loaded.您的问题是
numberRandom = getRandomInt(1, 7)
在页面加载时运行一次。 If you want a different number each button click, just move it inside the event listener如果您希望每个按钮单击一个不同的数字,只需将其移动到事件侦听器中
const roll = document.getElementById("roll")
roll.addEventListener('click',()=> {
numberRandom = getRandomInt(1, 7) // <=== move it here
alert(numberRandom)
})
Additionally, the calculation doesn't not appear to be correct, I believe it should be closer to此外,计算似乎不正确,我相信它应该更接近
Math.floor(Math.random() * (max - min + 1)) + min
If you want to generate a random number when you click then you need to put the code that generates a random number in the function that gets called when you click .如果要在单击时生成随机数,则需要将生成随机数的代码放入单击时调用的 function 中。
Putting it straight in the top level of the script means you generate a random number once as the page loads.将其直接放在脚本的顶层意味着您在页面加载时生成一个随机数。
Every time the function gets called you read the same number from the roll
variable.每次调用 function 时,您都会从
roll
变量中读取相同的数字。
function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min+1) ) + min; } const roll = document.getElementById("roll") roll.addEventListener('click',()=>{ var numberRandom = getRandomInt(1, 6) console.log('Dice rolled,you got ',numberRandom); })
<button class="favorite styled" type="button" id="roll"> Role dice </button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.