变量定义问题Javascript

时间:2015-05-26 00:13:58

标签: javascript html undefined

我正在尝试随机化一个字符串,具体取决于他们有多少玩家,并为每个玩家分配他们的工作/角色。在Chrome控制台中,我收到错误, “Uncaught ReferranceError:al未定义。”我不知道问题是什么,变量是在使用它之前定义的(在第一个按钮中定义,在第二个按钮中使用)。 我在文档中有一个警告,证明变量已定义,当按下按钮时,它在参数al中说明。 HTML:

    <input maxlength="1" id="input"> <button id="gp" onclick="gp()">Start!</button>
    <br/>
    <br/>
    <button id="DJ" onclick="DJ(al, rl);BlankDisplay(al, rl)">Display Your Job!</button>
    <br/>
    <span id="DS">1) Input Amount Of Players. 2)Click 'Display Your Job!'</span>

使用Javascript:

function gp(){
    players = document.getElementById("input").value;
    if(isNaN(players)){
        alert(players.toUpperCase() + "'s Players? Please Fix"); 
        return;
    }
    if(players === " "){
        alert("Please Define How Many People Are Playing!");
        return;
    }
    if(players === ""){
        alert("Please Define How Many People Are Playing!");
        return;
    }
    if(players < 4){
        alert("Sorry, You Need Atleast 4 Players To Play!");
        return;
    }
    SA(players)
}
function SA(players){
    var positions = ["Murderer", "Judge", "Innocent", "Innocent"]; //Pre-set positions
    if(players == 5){
        positions.push("Co-Judge");
    }else if(players == 6){
        positions.push("Innocent", "Co-Judge"); 
    }else if(players == 7){
        positions.push("Murderer-2!", "Innocent", "Co-Judge");
    }
    Randomize(players, positions)
}
function shuffle(o){
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
}
function Randomize(players, positions){
    var rl = shuffle(positions);
    var al = positions.length;
    confirm("You Have: " + al + " Players, Correct?");
    alert(al + ". " + rl);
}
function DJ(al, rl){
    var counter = 0;
    var bd = 0;
    for(var c = 0; c < al + 1; c++){
        if(counter == 0){
            document.getElementById("DS").innerHTML(rl[c]);
            document.getElementById("BJ").innerHTML("Click To Clear!");
            bd = 1;
        }
    }
}
function BlankDisplay(al, rl){
    if(bd == 1){
        document.getElementById("Click The Button Above To See Your Job!");   
    }
}

2 个答案:

答案 0 :(得分:1)

你有两个函数,DJ和BlankDisplay(从不使用大写字母),它们都接受al和rl的参数,但第二个函数不使用al或rl。然后在这段代码中:<button id="DJ" onclick="DJ(al, rl)你将变量al和rl传递给DJ的函数调用,但是除非你已经将var al和rl定义为window / global scope的属性,那么这些是未定义。

我猜你是否对变量和参数之间的区别感到困惑。所以我从那里开始。

答案 1 :(得分:1)

删除al&amp;来自DJ参数的rl。他们生活在全球范围内,应该可以访问al&amp; rl,无需通过DJ按钮onclick传递。

  • 更新按钮DJ,如下所示:<button id="DJ" onclick="DJ(); BlankDisplay();">Display Your Job!</button>
  • 在JS中的所有内容之前添加alrl,如下所示:var al, rl;
  • 在随机化中省略var。所以:var rl = shuffle(positions); var al = positions.length;应该成为:rl = shuffle(positions); al = positions.length;
  • 将此行function DJ(al, rl){更改为此function DJ(){
  • 将此行function BlankDisplay(al, rl){更改为此function BlankDisplay(){

应该这样做。