如果声明工作..?或不?

时间:2013-10-03 23:30:01

标签: javascript

满足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

2 个答案:

答案 0 :(得分: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{
...
}

答案 1 :(得分: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