我想根据用户在输入字段中填写的内容将其重定向到不同的页面。
示例:
- 当他输入1或2时,他将被重定向到谷歌
- 当他键入3或4时,他将被重定向到facebook
- 当他键入5时,他将被重定向到stackoverflow
else显示一条消息
尝试使用if else
语句和window.location.href
将用户引导到目标窗口。
function redirect() {
const inputVal = Number(document.getElementById("inputVal").value);
let url = "";
if (inputVal) {
if (inputVal === 1 || inputVal === 2){
url = "https://www.google.com"
} else if (inputVal === 3 || inputVal === 4){
url = "https://www.facebook.com"
} else {
console.log('Redirect Not Defined!!')
}
}
if (url) {
window.location.href = url
}
}
document.getElementById("redirectButton").addEventListener("click", redirect);
<input type="number" value=1 id="inputVal" />
<button type="button" id="redirectButton"> Redirect </button>
我通常不推荐switch语句,但这里它适用于
请注意,在SO处,动作可能会被阻止
document.getElementById("myForm").addEventListener("submit", function(e) {
let loc = "";
switch (+document.getElementById("inputVal").value) {
case 1:
case 2:
loc = "https://www.google.com";
break;
case 3:
case 4:
loc = "https://www.facebook.com"
break;
case 5:
loc = "https://stackoverflow.com";
break;
default:
console.log('Redirect Not Defined!!')
e.preventDefault(); // cancel submit
}
if (loc) this.action = loc;
})
<form id="myForm" target="_blank">
<input type="number" value=1 id="inputVal" />
<button type="submit"> Redirect </button>
</form>
这里有另一个可行的建议,使用对象作为地图,通过索引引用所需位置:
const EL = (sel, EL) => (EL || document).querySelector(sel);
const navigate = () => {
const addr = [
"google.com",
"facebook.com",
"stackoverflow.com",
];
const maps = {
1: 0,
2: 0,
3: 1,
4: 1,
5: 2,
};
const EL_num = EL("#num");
const url = addr[maps[EL_num.value]];
if (url) return location.assign(`https://${url}`);
console.log("Coudn't navigate");
};
EL("#go").addEventListener("click", navigate);
<input id="num" type="number" value="1">
<button id="go" type="button">Go</button>
比使用CCD_ 3或CCD_。