![](/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.