如果您运行此脚本并在提示框中输入 2,它永远不会运行其他脚本,我不知道为什么。是我设置 var 或 myFunction 的方式不正确吗?
<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<script type="text/javascript">
function myFunction()
{
var x=1;
var name=prompt("Please enter a number one");
if ( x===1)
{
alert("good");
}
else
{
alert("not a number 1");
}
}
</script>
</body>
</html>
你想检查x == name
.
您正在检查x === 1
这始终是正确的,因为您已经设置了x = 1
并且从未覆盖它。
此外,x === name
不起作用,因为prompt
返回一个字符串,而1
是一个数字。您可能需要设置x = '1'
然后检查x === name
是否要使用严格比较。
你永远不会将 x 分配给除 1 之外的任何内容!然后你检查它确实是整数 1。
将脚本更改为
if (prompt("Please enter a number one") != 1){
alert('Not a number 1');
} else {
alert('Good')
}
因为您要在脚本中定义x=1
,然后检查x === 1
。
也许你的意思是将用户输入分配给x
,但你没有这样做。
或者正如zzzzBov所说,也许你打算根据你的目的做x === name
或x == name
。