Javascript if语句不起作用

xjs*_*16x 5 javascript if-statement

非常直接的我想做的事情:

  • 如果输入是0,则意味着他们没有输入数字,它应该告诉你.
  • 当输入是7,它应该说你做对了.
  • 还有别的,它应该告诉你,你弄错了.

但无论输入是什么,它只输出"7是正确的"线,我无法弄清楚出了什么问题.

<script type="text/javascript">
function problem2 ()
{
var number = 0;
var text=document.getElementById("output");
number = prompt("Enter a number between 1 and 10 please" , 0);
if (number = 0)
    {
     text.value = "You didn't enter a number!";
    }
if (number = 7)
    {
     text.value = "7 is correct!";
    }
else
    {
     text.value = "Sorry, ", input, "is not correct!";
    }
}
</script>
<input type="button" value="Click here" onclick="problem2()">
<input id="output" type="text">
Run Code Online (Sandbox Code Playgroud)

Jos*_*osh 6

你正在分配=.使用=====.

if( 0 == number ){

  text.value = "You didn't enter a number!";
}
Run Code Online (Sandbox Code Playgroud)

另外,要小心你的支架放置.Javascript喜欢自动添加分号到行尾.来源.

  • 在上面的例子中使用`===`将不起作用,因为`prompt()`的返回值是一个字符串.你需要使用`if(number ==="7")......` (2认同)