如何将用户发送到基于文本输入对象的新网页



我正在尝试创建一个文本冒险游戏。在其中,用户在文本输入框中键入命令。根据命令,它们将被发送到另一个网页。以下是我的HTML:

<input type="text" id="a" onchange="text()" value=""/>

以下是我所拥有的javascript:

function text(){
var input = document.getElementById("a").value;
switch(input){
case "run":
window.location.replace("1_2.html");
case "rescue":
window.location.replace("1_3.html");
}
}

但是,如果它们键入run或rescue,它会将它们发送到1_3.html。我曾尝试将window.location.replacewindow.location.href切换,但它们既没有被转换为1_3.html,也没有转换为1_2.html。我也尝试过使用if else if else,但它得到了相同的结果和问题。我该怎么办?

你可以像一样完成

function text(){
var input = document.getElementById("a").value;
switch(input.toLowerCase()){
case "run":
window.location.replace("1_2.html");break;
case "rescue":
window.location.replace("1_3.html");break;
}
}

因为您的输入可能包含大写和小写

查看切换语句的正确语法

function text(){
var input = document.getElementById("a").value;
switch(input){
case "run":
window.location.replace("1_2.html");
break;
case "rescue":
window.location.replace("1_3.html");
break;
default:
console.log("Default case");
}
}

如果省略break语句,即使评估与案例(来自w3schools(不匹配,也将执行下一个案例

你可以这样做在Cases之后添加Break;

case "run":
window.location.replace("1_2.html");break;
case "rescue":
window.location.replace("1_3.html");break;

最新更新