我正在制作一个非常简单的故事"游戏"哪里有选择的问题(不是单选按钮等),用户必须键入给他们的选择。我不会很好用JavaScript,因为你会看到......
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="gamescript.js"></script>
</head>
<body>
<p id ="door"> Which door do you wish to enter? Door 1 or Door 2? </p>
<input id="myInput" type="text">
<button onclick="myFunction()">Enter</button>
<script>
function myFunction(){
var door = document.getElementById("myInput").value;
if (door == "Door 1", "door 1"){
document.getElementById("door").innerHTML = "You have entered" + door;
}else if (door == "Door 2", "door 2"){
document.getElementById("door").innerHTML = "You have entered" + door;
}else{
document.getElementById("door").innerHTML = "You must enter a door!"
}
}
</script>
</body>
</html>
我没有收到任何错误,但是当我输入一些随机的东西/或留空时,它的意思是说&#34;选择一扇门&#34;但是它会在文本框中显示我输入的任何内容。这段代码可能是错的,我猜它最有可能是......我不想上网寻求帮助,但没有其他人可以问。所有帮助表示赞赏。谢谢。
答案 0 :(得分:2)
您if
语句的语法错误。更改您的if
语句以使用正确的&#34;或&#34;语法:
function myFunction(){
var door = document.getElementById("myInput").value;
if (door == "Door 1" || door == "door 1"){
document.getElementById("door").innerHTML = "You have entered" + door;
}else if (door == "Door 2" || door == "door 2"){
document.getElementById("door").innerHTML = "You have entered" + door;
}else{
document.getElementById("door").innerHTML = "You must enter a door!"
}
}
&#13;
<body>
<p id ="door"> Which door do you wish to enter? Door 1 or Door 2? </p>
<input id="myInput" type="text">
<button onclick="myFunction()">Enter</button>
</body>
&#13;
答案 1 :(得分:1)
您可以使用ot toLowerCase()然后将door
与“门1”等进行比较。
function myFunction(){
var door = document.getElementById("myInput").value.toLowerCase();
if (door == "door 1"){
document.getElementById("door").innerHTML = "You have entered" + door;
}else if (door == "door 2"){
document.getElementById("door").innerHTML = "You have entered" + door;
}else{
document.getElementById("door").innerHTML = "You must enter a door!"
}
如果您需要,可以使用||
(或)logical operator并评估if (door == "Door 1" || door =="door 1")
答案 2 :(得分:1)
为什么不使用简单的开关,而不是在不同的条件下执行相同的代码行?
<!DOCTYPE HTML>
<html>
<body>
<p id ="door"> Which door do you wish to enter? Door 1 or Door 2? </p>
<input id="myInput" type="text">
<button onclick="myFunction()">Enter</button>
<script>
function myFunction(){
var door = document.getElementById("myInput").value;
switch(door.toLowerCase()) {
case 'door 1':
case 'door 2':
document.getElementById("door").innerHTML = "You have entered" + door;
break;
default:
document.getElementById("door").innerHTML = "You must enter a door!"
}
}
</script>
</body>
</html>
&#13;
答案 3 :(得分:0)
comma operator ,
计算每个操作数(从左到右)并返回最后一个操作数的值。您的问题是第一个if
检查始终返回true。
function myFunction(){
var doorVal = document.getElementById("myInput").value;
var door = document.getElementById("door");
// this could just as well be an object
var acceptedResponses = ["Door1", "door1", "Door2", "door2"];
if (acceptedResponses.indexOf(doorVal) !== -1) {
door.innerHTML = "You have entered " + door;
} else {
door.innerHTML = "You must enter a door!";
}
}