需要答案和更新的Javascript框

时间:2015-09-08 08:19:00

标签: javascript

我已经花了好几个小时尝试不同的东西并且无法让它工作,我已经制作了一个每10秒滚动一次的骰子,计时器和骰子滚动显示在屏幕上并不断更新滚动。我想制作一个显示前五个掷骰子并不断更新的方框。不确定我是否必须单独创建功能或将其添加到现有功能中。这是我到目前为止所拥有的。

way-

2 个答案:

答案 0 :(得分:0)

你所需要的只是追加。检查添加了status.innerHTML += "Dice Roll "+diceTotal+".<br>";

的代码段

&#13;
&#13;
var timeInSecs;
var ticker;

function startTimer(secs) {
  timeInSecs = parseInt(secs);
  ticker = setInterval("tick()", 1000); 
}

function tick( ) {
  var secs = timeInSecs;

  if (secs > 0) {
    timeInSecs--; 
  }

  else {
    var die1 = document.getElementById("die1");
    var status = document.getElementById("status");
    var d1 = Math.floor(Math.random() * 6) + 1;
    var diceTotal = d1;
    die1.innerHTML = d1;
    status.innerHTML = "Dice Roll "+diceTotal+".<br>" +status.innerHTML;
    clearInterval(ticker);
    startTimer(0000010);  // start again
  }


  var mins = Math.floor(secs/60);
  secs %= 60;
  var pretty = ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
  document.getElementById("countdown").innerHTML = pretty;
}

startTimer(0000010);  
&#13;
<div id="countdown"></div> <div id="die1" class="dice">0</div> <h2 id="status" style="clear:centre;"></h2> 
&#13;
&#13;
&#13;

答案 1 :(得分:0)

一个选项是拥有5个预定义的div并动态清除/填充它们。 另一种选择是将滚动历史记录保存在一个数组中并填充“历史记录元素”。从那个阵列。

例如:

rolls.push(d1); //add roll to history
if(rolls.length > maxrollhistory)
     rolls.shift();            
die1.innerHTML = 'Previous rolls: ' + rolls.reduce(function(prev,cur){return '<span class="rollhistory">' + cur + ' </span>' + prev; }, '');

其中rolls是包含历史记录的数组。 (rollhistory是我用来格式化结果的一个类。)

在基础示例中,我冒昧地重组程序以显示上述内容(click here for fiddle):

var die1 = document.getElementById("die1"),
    status = document.getElementById("status");

function startTimer(secs) {

    var timeInSecs = parseInt(secs),        
        rolls = [],
        rem = 0, 
        maxrollhistory = 5,    
        roll = function(){
            var d1 = Math.floor(Math.random() * 6) + 1;
            rolls.push(d1); //add roll to history
            if(rolls.length > maxrollhistory)
                rolls.shift();            
            die1.innerHTML = 'Previous rolls: ' + rolls.reduce(function(prev,cur){return '<span class="rollhistory">' + cur + ' </span>' + prev; }, '');
            status.innerHTML = "Dice Roll "+ d1 +".";
        },    
        tick = function(){       
            if (--rem <= 0) {
                rem = timeInSecs;
                roll();
            }

            var secs = rem;
            var mins = Math.floor(secs/60);
            secs %= 60;
            var pretty = ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
            document.getElementById("countdown").innerHTML = pretty;

            setTimeout(tick,1000);
        }

    tick();
}

startTimer(10);