[英]adding an event listener to roll dice javascript
我目前正在上課的初學者JavaScript程序。
該程序應向用戶顯示兩個輸入字段。 第一個輸入字段將接受一個整數,該整數將確定管芯將具有多少側。 第二個輸入將接受一個整數,該整數將確定擲出骰子的次數。
這些輸入必須經過驗證只能是正數。 輸入輸入后,用戶單擊輸入字段之外的內容,將觸發addEventListener('blur')
並且將“擲出”骰子。 例如,應顯示You rolled: 6, 2, 3, 5 for a total roll of 16
。
建議我們使用一個循環來執行骰子的“擲骰”。 發生模糊事件時,循環次數應根據需要執行,並應顯示單個滾動和總和。
我的問題是:
我將如何存儲從擲骰子到數組中的次數開始的輸入值,然后循環遍歷該數組以顯示每個擲骰子的隨機數以及總擲骰數? 每當兩個輸入字段發生模糊事件時,都會發生這種情況。
目前,我的程序僅顯示來自模具側輸入和投擲量輸入的隨機數。 我嘗試為此任務使用for或while循環,但未成功。 這就是我目前所擁有的。
function dieInfo() { // temporary label to display # of sides var dieSideNum = document.getElementById('die-side-num'); // convert string input into floating integer, // if this doesnt create a number use 0 instead var getDieSide = parseFloat(dieSideQuant.value) || 0; // temporary label to display throw total var throwTotal = document.getElementById('throw-total'); //convert string input into floating integer // if this doesnt create a number use 0 instead var getThrowTotal = parseFloat(throwQuant.value) || 0; // if die sides input or throw amount input is <= 0 if (getDieSide <= 0 || getThrowTotal <= 0) { // display error for improper number of sides for die input dieSideNum.textContent = "Please enter valid Die sides"; // display error for improper throw amount input throwTotal.textContent = "Please enter valid throw amount"; } else { // use random function to store random number from die sides input throwRand = Math.floor(Math.random() * (1 + (getDieSide) - 1)) + 1; // test- display random number of sides for die dieSideNum.textContent = "Number of Sides on Die: " + throwRand; // test - display throw count throwTotal.textContent = " You threw " + getThrowTotal + "times"; } } // retrieve id for for amount of sides on die var dieSideQuant = document.getElementById('die-side-quant'); // fire the dieInfo function when the input element loses focus dieSideQuant.addEventListener('blur', dieInfo); // retrieve id for throw amount input var throwQuant = document.getElementById('throw-quant'); // fire the dieInfo function when the input element loses focus throwQuant.addEventListener('blur', dieInfo);
<h1 id="info-die"> How many sides on die? </h1> <input type="number" min="0" id="die-side-quant" placeholder="# sides on die"> <h3 id="die-side-num"></h3> <h1 id="info-throw-die"> Throw Amount? </h1> <input type="number" min="0" id="throw-quant" placeholder="throw amount"> <h3 id="throw-total"></h3>
要存儲擲骰子進入數組的次數的輸入值,請聲明Array
並使用.push
方法。
// declare an Array variable
var dieThrows = [];
// use .push to store the value in the Array.
dieThrows.push(throwRand);
// or don't bother with the extra throwRand variable by doing it this way
dieThrows.push(Math.floor(Math.random() * (1 + (getDieSide) - 1)) + 1);
要遍歷數組,請使用.forEach
方法或僅遍歷值:
// doing it ES5-style:
dieThrows.forEach(function (throwResult, index, array) {
console.log(throwResult); // display the random numbers for each die throw in the dev tools console
});
// doing it ES6-style:
dieThrows.forEach( (throwResult, index, array) => (console.log(throwResult)) );
// doing it old-school:
for (var i = 0; i < dieThrows.length; i += 1) {
console.log(throwResult); // display the random numbers for each die throw in the dev tools console
}
要獲得總的拋出次數,您可以訪問Array的.length
屬性(因為您將每次拋出都存儲在Array中):
var totalThrows = dieThrows.length;
var numRolls = 6;
var numRollTotal = 0;
for(var i = 0; i < numRolls; i++) //Here happens the for magic.
{
//Write and store
}
//Write again
我故意留了一些空白;)查看您的代碼,您足夠聰明地將其弄清楚。 無需在此陣列。
您已經正確識別了子問題! 您可以參考以下內容:
window.onload = function() { document.getElementById('numThrows') .addEventListener('blur', function() { var numSides = parseInt(document.getElementById('numSides').value); var numThrows = parseInt(document.getElementById('numThrows').value); var randArr = []; for (var i = 0; i < numThrows; i++) // On each repetition, store a result into `randArr` randArr.push(1 + Math.floor(Math.random() * numSides)); // Now display the results var results = document.getElementById('results'); results.innerHTML = randArr.map(function(randNum, throwNum) { // Generate HTML markup for each result return '<div class="result">' + 'Throw #' + (throwNum + 1) + '; ' + 'result: ' + randNum + '</div>'; }).join(''); }); };
<div>Note this example has no validation</div> <input id="numSides" placeholder="sides" type="text"/> <input id="numThrows" placeholder="throws" type="text"/> <div id="results"> </div>
document.getElementById('throw-quant')
.addEventListener('blur', function(){
var numSides = parseInt(document.getElementId('die-side-quant').value);
var numThrows = parseInt(document.getElementId('throw-quant').value);
var outputString="You rolled:";
var total=0;
for(var i=0; i<numThrows; i++){
var n = Math.floor(Math.random() * (1 + (getDieSide) - 1)) + 1;
total+=n;
outputString+=" "+String(n);
}
outputString+=" for a total roll of "+String(total);
document.getElementById("desired location").innerHTML = "<p>"+outputString+"</p>"
})
我希望這有幫助。 期望的位置是您希望顯示結果的標簽的ID。
// Global variables // var id_dieSideQuant = document.getElementById('id_dieSideQuant'), // retrieve id for for amount of sides on die id_throwQuant = document.getElementById('id_throwQuant'); // retrieve id for throw amount input var id_throwTotal = document.getElementById('id_throwTotal'), // local varible to function only for displaying the throw total id_dieSideNum = document.getElementById('id_dieSideNum'); // local varible to function only for displaying number of sides // Functions // function dieInfo() { // Hide and clear up the text-fields // id_dieSideNum.parentElement.classList.remove("container1"); document.getElementById('id_throwTotal').innerHTML = ""; document.getElementById('id_dieSideNum').innerHTML = ""; // // Local variables /* convert string input into floating integer, if this doesnt create a number use 0 instead */ var getDieSide = parseFloat(id_dieSideQuant.value) || 0, getTotalThrows = parseFloat(id_throwQuant.value) || 0, randThrow, allDieThrows = []; // // Errors if (getDieSide < 2 && id_dieSideQuant.value.length !== 0) { // if die sides input < 2 id_dieSideNum.innerHTML = "<span style='color: red'>Please enter a valid total of die sides; min. 2.</span>"; // display error for improper number of sides for die input } if (getTotalThrows < 1 && id_throwQuant.value.length !== 0) { // if die throw amount input is < 1 id_throwTotal.innerHTML = "<span style='color: red'>Please enter a valid throw amount.</span>"; // display error for improper throw amount input } if (getDieSide < 2 || getTotalThrows < 1 || (new RegExp(/\\d+(?!\\.)/).exec(getDieSide.toString())["index"] !== 0 || new RegExp(/\\d+(?!\\.)/).exec(getTotalThrows.toString())["index"] !== 0)) return false; // Exit if there is something wrong. "/\\d+(?!\\.)/" checks that there is no comma // // if (id_dieSideQuant.value.length !== 0 && id_throwQuant.value.length !== 0) { // Throw the die // for (var i = 0; i < getTotalThrows; i++) { // throw the dice the total amount of throws using a standard for-loop randThrow = Math.floor(Math.random() * getDieSide) + 1; // use random function to store random number from die sides input allDieThrows.push(randThrow); } // Display result // id_throwTotal.innerHTML = `Total throws: ${getTotalThrows}`; // test- display random number of sides for die id_dieSideNum.innerHTML = "Your die landed on:<br><br>"; // test - display throw count for (var i = 0; i < allDieThrows.length; i++) { id_dieSideNum.innerHTML += "Throw #" + (i + 1) + ": " + allDieThrows[i] + "<br>"; } id_dieSideNum.parentElement.classList.add("container1"); } } // Event Listeners // id_dieSideQuant.addEventListener('input', dieInfo); // fire the 'dieInfo' function when the input element is changed (use: 'input' || 'change') id_throwQuant.addEventListener('input', dieInfo); // fire the 'dieInfo' function when the input element is changed (use: 'input' || 'change') id_button0.addEventListener('click', dieInfo); // fire the 'dieInfo' function when the input element is changed
body { color: olivedrab; font-family: sans-serif; background-color: #222; } .container0 { padding: 10px; border: 1px solid orange; border-radius: 10px; margin-left: 20px; } .container1 { padding: 5px; border: 2px solid orangered; border-radius: 5px; margin-left: 20px; margin-top: 10px; }
<h1>Die-roller</h1> <div class="container0"> <h2 id="id_infoThrowDie">Throw Amount? <button id="id_button0">Update throw</button></h2> <input id="id_throwQuant" type="number" min="1" step="1" placeholder="Throw amount"> (min. 1 throw) <h3 id="id_throwTotal"></h3> <h2 id="id_infoDie">How many sides on die?</h2> <input id="id_dieSideQuant" type="number" min="2" step="1" placeholder="Sides on die"> (min. 2 sides) <div> <h3 id="id_dieSideNum"></h3> </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.