2015-05-27 2 views
0

я создал кнопку с помощью JavaScript, и у меня есть список, который должен получить случайное число, когда я «бросить кости»Как динамически создавать кнопки на основе случайных условий

мне нужно перечислить номера сказать «Вы прокатили 1», например. Как мне это сделать? А также мне нужно только показать последние 10 номеров.

var rollNumber = 0; 
var values = []; 

function dieRolled() { 
    rollNumber += 1; 
    var numRolled = Math.ceil(Math.random() * 6); 
    values.push(numRolled); 
    document.getElementById("results").innerHTML = ""; 

    for (var x = values.length-1 ; x>=0; x--) { 
     var newRoll = document.createElement("li"); 
     newRoll.innerHTML = values [x] +"You rolled a"; 
     document.getElementById("results").appendChild(newRoll); 
     if (x == 11)break; 
    } 

} 

ответ

2

Как насчет этого?

\t var output = document.getElementById("Output"); 
 
\t var values = []; 
 
\t 
 
\t function roll() 
 
\t { 
 
\t \t values.push(Math.ceil(Math.random() * 6)); 
 
\t \t 
 
\t \t // If the history is too big, drop the oldest... 
 
\t \t if (values.length > 10) 
 
\t \t { 
 
\t \t \t values.shift(); 
 
\t \t } 
 
\t \t 
 
\t \t // Rewriting the history log 
 
\t \t var text = ""; 
 
\t \t for (var i in values) 
 
\t \t { 
 
\t \t \t text += "You rolled a " + values[i] + "\n"; 
 
\t \t } 
 
\t \t 
 
\t \t output.innerHTML = text; 
 
\t } 
 
\t 
 
\t // Rolling multiple times 
 
\t setInterval(function(){ roll(); }, 1000);
<pre id="Output"></pre>

2

Попробуйте это:

var list = document.getElementById('demo'); 
 
var count = 0; 
 
function changeText2() { 
 
    count++; 
 
    if(count <= 10) 
 
    { 
 
    var numRolled = Math.ceil(Math.random() * 6); 
 
    var entry = document.createElement('li'); 
 
    entry.appendChild(document.createTextNode("You rolled:"+numRolled)); 
 
    list.appendChild(entry); 
 
    } 
 
}
<input type='button' onclick='changeText2()' value='Submit' /> 
 
<p>Dices you rolled</p> 
 
<ol id="demo"></ol>

Смежные вопросы