单击基本JS到DOM,无需双重运行效果

时间:2016-02-18 10:24:30

标签: javascript dom dom-manipulation

我是开发新手,对于一些学习实践我正在做这个可以打印到DOM Dice Roller的香草JS。

主要思想是让用户输入边数和骰子数,按下掷骰子并获取所有骰子结果和DOM上的总和。

它正在运作,但我无法弄清楚为什么我需要点击两次才能发生此事件,请提供任何提示?

http://codepen.io/rufi_rufino/pen/MKdrbj

//Variables

var form = document.getElementById('mytest');
var sideField = document.getElementById('sides');
var numberField = document.getElementById('numbofdices');
var numberOfSides = 0;
var numberOfDice = 0;
var arrayOfResults = [];
var resultOfSum = 0;


//to get dice data (sides and # of dices) form html forms - Using .preventdefault() to stop from sending form and staying with result;

form.addEventListener('submit', function(e) {
//to get the value of the number of sides the dice has:
    numberOfSides = (sideField.value);
//to get the value of the number of dices in the game:
    numberOfDice = (numberField.value);    
    e.preventDefault();

});



//Basic Functions

//function to calculate a result and create the array of all results
function createArrayOfDice () {

    for (i = 1 ; i <= numberOfDice ; i++) {

        var result = 0;
        result = Math.floor((Math.random() * numberOfSides) + 1);
        arrayOfResults.push(result);

    }

}

// function to sum the results of all dice
function sumOfAllDices() {

    // the line below "resets" the output if user clicks more than once
    document.getElementById("results").innerHTML = " ";

    for (i = 0 ; i < arrayOfResults.length ; i++) {


        resultOfSum = resultOfSum + arrayOfResults[i];
        document.getElementById("results").innerHTML = document.getElementById("results").innerHTML + "<div class='diceroll'>" + arrayOfResults[i] + "</div>";

    }

    console.log(resultOfSum);
    document.getElementById("sum").innerHTML = "<div class='dicesum'>" + resultOfSum + "</div>";
    resultOfSum = 0;

}

//function that works when user clicks the 'Roll' submit button on html
function myClick () {

    createArrayOfDice();
    // for console purpose(see if it is wokring)
    console.log(arrayOfResults);
    sumOfAllDices();
    // for console study only
    console.log ("The input number for how many sides the dice has is:" + numberOfSides);
    console.log ("The input number for the number of dices is:" + numberOfDice);
    arrayOfResults = [];

};

如果有人可以提供帮助,我感激不尽。这也是我的第一个问题,如果我犯了任何错误,我很乐意将其考虑在内。

0 个答案:

没有答案