-1

当我单击 2 个单选按钮中的任何一个时,文本会重叠。我希望 if else 条件单独运行。这意味着当我单击较高的单选按钮时,它会检查 playertotal 是否高于 computertotal 并写入结果。与下部单选按钮相同。

这属于更长的代码:

function button1()
{
    // Checks if it's the players turn
    if(playerturn==true)
    {
        // Generates eyes for the dice
        var eyes3=Math.floor(Math.random()*6)+ 1;
        var eyes4=Math.floor(Math.random()*6)+ 1;
        //Shows the eyes
        showEyes(eyes3, 325);
        showEyes(eyes4, 450);

        computerturn=true;
        playerturn=false;

        playerTotal = eyes3+eyes4;
        //Checks if player has won
        if (higher=1 && playerTotal > computerTotal) 
        {
            pen.font = '20pt Calibri';
            pen.fillText('You have won',300,250);
        }
        else if (higher=1 && playerTotal < computerTotal) 
        {
            pen.font = '20pt Calibri';
            pen.fillText('You have lost',300,250);
        }

        if (lower=1 && playerTotal < computerTotal) 
        {
            pen.font = '20pt Calibri';
            pen.fillText('You have won!',300,250);
        }
        else if (lower=1 && playerTotal > computerTotal) 
        {
            pen.font = '20pt Calibri';
            pen.fillText('You have lost',300,250);
        }
    }
}

function higherRadioButton()
{
    higher = 1
    lower = 0
}

function lowerRadioButton()
{
    lower = 1
    higher = 0
}

谢谢你。

4

1 回答 1

0

在 JavaScript 中,比较运算符是==,而不是=。您的代码应如下所示:

if (higher == 1 && playerTotal > computerTotal) 
{
    //...
}

对于所有其他陈述也是如此。

为避免将来出现此类问题,请始终将数字放在左侧:

if (1 == higher && playerTotal > computerTotal) 
{
    //...
}

这样,如果您忘记了一个“=”,您将得到错误而不是错误的结果。

于 2012-12-10T09:02:18.547 回答