1

当满足 if 语句要求时,不会显示我的显示中奖消息

//start check function
function check(){

    if(box1 >= 1 && box1 <= 6 && box2 >= 1 && box2 <= 6 && box3 >= 1 && box3 <= 6) 
    {
            //display wining message
            document.getElementById('header').textContent = 'Congrats! You win 1 credit.';

            //add one credit when you get 3 reds
            creditCounter = creditCounter + 1;
    }
    if(box1 >= 7 && box1 <= 9 && box2 >= 7 && box2 <= 9 && box3 >= 7 && box3 <= 9) 
    {       
            //display wining message
            document.getElementById('header').textContent = 'Congrats! You win 10 credit.';

            //add 10 credits when you get 3 green
            creditCounter = creditCounter + 10;
    }
    if(box1 == 10 && box2 == 10 && box3 == 10) 
    {
            //display wining message
            document.getElementById('header').textContent = 'Congrats! You win 100 credit.';    

            //add 100 credits when you get 3 blue
            creditCounter = creditCounter + 100;
    }
    else{
           //display losing message
           document.getElementById('header').textContent = 'Sorry, please try again.';
    }
}//END check() function
4

2 回答 2

3

您缺少“else if”,因此对于满足获胜条件的情况,最后的“else”将继续进行。

看我的小提琴:http: //jsfiddle.net/E9CMA/2/

if(box1 >= 1 && box1 <= 6 && box2 >= 1 && box2 <= 6 && box3 >= 1 && box3 <= 6) 
{
...
}

else if(box1 >= 7 && box1 <= 9 && box2 >= 7 && box2 <= 9 && box3 >= 7 && box3 <= 9) 
{       
...
}

else if(box1 == 10 && box2 == 10 && box3 == 10) 
{
...
}
else{
...
}
于 2013-10-03T23:44:46.903 回答
1

一旦满足条件,您需要停止检查,使用return.. 执行此操作,例如:

//start check function
function check(){

    if(box1 >= 1 && box1 <= 6 && box2 >= 1 && box2 <= 6 && box3 >= 1 && box3 <= 6) 
    {
        //display wining message
        document.getElementById('header').textContent = 'Congrats! You win 1 credit.';

        //add one credit when you get 3 reds
        creditCounter = creditCounter + 1;

        return; // they won 1 credit.. finish checking
    }
    if(box1 >= 7 && box1 <= 9 && box2 >= 7 && box2 <= 9 && box3 >= 7 && box3 <= 9) 
    {       
        //display wining message
        document.getElementById('header').textContent = 'Congrats! You win 10 credit.';

        //add 10 credits when you get 3 green
        creditCounter = creditCounter + 10;

        return; // they won 10 credits.. finish checking
    }
    if(box1 == 10 && box2 == 10 && box3 == 10) 
    {
        //display wining message
        document.getElementById('header').textContent = 'Congrats! You win 100 credit.';    

        //add 100 credits when you get 3 blue
        creditCounter = creditCounter + 100;
    }
    else{
       //display losing message
       document.getElementById('header').textContent = 'Sorry, please try again.';
    }
}//END check() function
于 2013-10-03T23:37:54.607 回答