简体   繁体   English

if else if 语句没有按我想象的方式工作

[英]the if else if statement not working the way I thought would have worked

I was making a winner checking system where, if I get 2 same numbers from a die than the innerHTML of the result should change from 'result' to 'you win,', if I didn't get same numbers, then the innerHTML of the 'p' should keep showing 'keep trying' but the if else if statement I was working with didn't give me the output I needed and instead of showing 'You win' or 'keep trying' in different cases.我正在制作一个获胜者检查系统,如果我从骰子中得到 2 个相同的数字,那么结果的 innerHTML 应该从“结果”变为“你赢”,如果我没有得到相同的数字,那么 innerHTML 的“p”应该继续显示“继续尝试”,但是我正在使用的 if else if 语句没有给我我需要的 output,而不是在不同情况下显示“你赢”或“继续尝试”。 it keeps showing 'you win' when clearly my both numbers don't match with each other.当我的两个数字明显不匹配时,它一直显示“你赢了”。

here's the js code:这是js代码:

var dice1 = document.getElementById('you');
var dice2 = document.getElementById('cpu');
var result = document.getElementById('rslt');
var button = document.getElementById('btn');

// Button Interaction

function randomNumbers() {
  document.getElementById('you').innerHTML = Math.floor(Math.random() * 6);
  document.getElementById('cpu').innerHTML = Math.floor(Math.random() * 6);
}

// Result

function checkWin() {
  if (you.innerHTML == cpu.innerHTML) {
    return rslt.innerHTML = "You Win!";

  } else if (you.innerHTML != cpu.innerHTML) {
    return rslt.innerHTML = "Keep on trying!";

  } else {

    return rslt.innerHTML = "Keep on trying!";
  }
}

checkWin();

Please tell me what mistake I did.请告诉我我犯了什么错误。 I'm a novice in programming with javascript, so please dont bully me.我是 javascript 编程的新手,所以请不要欺负我。

Thank you if you read this far!谢谢你读到这里!

Wrap into variables and then try to use if else or as you already did with dice1 and dice2包装成变量,然后尝试使用 if else 或您已经使用 dice1 和 dice2

  var you = document.getElementById('you').innerHTML = Math.floor(Math.random()*6);
  var cpu = document.getElementById('cpu').innerHTML = Math.floor(Math.random()*6);

if(you == cpu)

You should call checkwin() when you button is pressed按下按钮时应该调用checkwin()

Try this code试试这个代码

  var dice1 = document.getElementById('you');

    var dice2 = document.getElementById('cpu');

    var result = document.getElementById('rslt');

    var button = document.getElementById('btn');

    // Button Interaction

    function randomNumbers(){

    document.getElementById('you').innerHTML = Math.floor(Math.random()*6);
    document.getElementById('cpu').innerHTML = Math.floor(Math.random()*6);
    checkWin();
    }

    // Result

    function checkWin(){

    if(you.innerHTML == cpu.innerHTML)

    { return rslt.innerHTML = "You Win!";

    } else if (you.innerHTML != cpu.innerHTML)

    { return rslt.innerHTML = "Keep on trying!";

    } else {

        return rslt.innerHTML = "Keep on trying!";
    }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM