抽奖的东西不起作用

时间:2018-04-23 21:25:29

标签: javascript

抽奖的编码问题不起作用!

var i = 0;
var count;
var names = [
    "Stefon",
    "Garret",
    "Brandon"
];

function GetRandomInt(){
    return Math.floor(Math.random()*i+1);
}

function CallWinner(){
    var ID = GetRandomInt();
    document.write("<hr>"+names[ID]+" has won with the ID of "+id+"!");
}

do {
    i++;
    for(count=0;i<=names.length;){
        count++;
        document.write(names[count]+" has been assigned to the raffle ID, "+count+"<br>");
    }
} while (i<=names.length);

由于某些原因,这不起作用,它就像一个无限循环或者它可能会崩溃选项卡,它可以工作,但它会崩溃选项卡。请帮忙。

1 个答案:

答案 0 :(得分:0)

document.write是document.wrong。请使用更现代,更不容易做混乱的事情。此函数尝试写入当前文档。如果文档已经处理完毕,则文档将替换为带有参数的空白文档。你不希望这样;改为使用正确的DOM方法。

您的GetRandomInt功能已损坏;它应该返回数组中的随机可访问索引,而不是静态数字。

尝试这样的事情:

const names = [
  "Stefon",
  "Garret",
  "Brandon"
];

function GetRandomIndex() {
  return Math.floor(Math.random() * names.length);
}

function CallWinner() {
  const index = GetRandomIndex();
  const hr = document.body.appendChild(document.createElement('hr'));
  hr.textContent = names[index] + " has won with the ID of " + index + "!";
}
names.forEach((name, count) => {
  const div = document.body.appendChild(document.createElement('hr'));
  div.textContent = name + " has been assigned to the raffle ID, " + count;
});
CallWinner();