![](/img/trans.png)
[英]I have a number and I would like to get the closest number less than and closest number greater than inside a jquery array
[英]hello, I would like to have a different random number, but I always get the same, an idea?
当我“单击”按钮#roll 时,我希望有一个不同的随机数,但我总是得到相同的数字。 有人可以帮我吗?
这是我的代码:
//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>
您的问题是numberRandom = getRandomInt(1, 7)
在页面加载时运行一次。 如果您希望每个按钮单击一个不同的数字,只需将其移动到事件侦听器中
const roll = document.getElementById("roll")
roll.addEventListener('click',()=> {
numberRandom = getRandomInt(1, 7) // <=== move it here
alert(numberRandom)
})
此外,计算似乎不正确,我相信它应该更接近
Math.floor(Math.random() * (max - min + 1)) + min
如果要在单击时生成随机数,则需要将生成随机数的代码放入单击时调用的 function 中。
将其直接放在脚本的顶层意味着您在页面加载时生成一个随机数。
每次调用 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.