我正在尝试使用提交按钮处理一些JavaScript功能,但似乎无法获得正确的结果。
在页面上heat-pull.php我有一个计划按钮,点击时会提示用户写一周中的某一天。单击时会打开一个提示框。
function show_prompt()
{
var day=prompt("For Which Day?");
var startTime=prompt("The Start Time?");
var endTime=prompt("The End Time?");
if (day=="Monday" || "Tuesday"
|| "Wednesday"
|| "Thursday"
|| "Friday"
|| "Saturday"
|| "Sunday")
{
alert("Your Schedule Has Been Set");
} else
alert("Scheduling Error, Try Again.")
window.location ="heating-pull.php";
}
如果他们写了一周中正确的一天,我希望他们转到我发送给他们的页面(schedule.php),如果他们没有输入正确的一天我想重新加载页面而不是让他们过去。
JavaScript新手,虽然我在这个地方寻找答案,但我不知道有什么不对。任何帮助都会很棒。欢呼声。
答案 0 :(得分:2)
您在if语句中的条件不正确。请改用
使用
if (day == "Monday" || day == "Tuesday" || day == "Wednesday" || day == "Thursday" || day == "Friday" || day == "Saturday" || day == "Sunday") {
//Do something
};
或强> 的
if (["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"].indexOf(day) > -1) {
//Do something
};
根据评论 我希望重定向能够刷新页面,以便用户再次填写表单。
你应该使用
window.location.href = window.location.href;
或强> 的
document.location.reload(true);
Location.reload()方法从当前网址重新加载资源。
完整代码
function show_prompt() {
var day = prompt("For Which Day?");
var startTime = prompt("The Start Time?");
var endTime = prompt("The End Time?");
if (day == "Monday" ||
day == "Tuesday" ||
day == "Wednesday" ||
day == "Thursday" ||
day == "Friday" ||
day == "Saturday" ||
day == "Sunday"
) {
alert("Your Schedule Has Been Set");
window.location.href = window.location.href;
} else {
alert("Scheduling Error, Try Again.")
window.location = "heating-pull.php";
}
}
答案 1 :(得分:0)
首先是一些解释。
使用if
语句时,||
并不意味着这样:
x is equal to 5 or 6 or 7 or 8 or 9
其中x将是其中之一。 ||
用于分隔条件:
condition1 or condititon2 or contition3
condition1 || condition2 || condititon3
在您的代码中,您拥有第一个条件:
day=="Monday" = condition1
"Tuesday" = condition2
...
"Sunday" = conditionN
在javascripts Strings
中,只有空字符串计算为false。所以我们可以像这样重写你的条件:
day=="Monday" || true || true || true || true ...
如果您想使用&&
和||
,则必须在它们之间设置条件。但有时候使用数据结构来寻找某些东西是值得的。
在你的情况下,你可能会有像
这样的东西// Make this as global as possible but not in window obviously
DaysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
// Freeze the object so nothing can modify it later... you wouldn't want to end up
// with "Caturday" instead of "Sunday"
Object.freeze(DaysOfTheWeek);
function show_prompt()
{
var day=prompt("For Which Day?");
var startTime=prompt("The Start Time?");
var endTime=prompt("The End Time?");
if(DaysOfTheWeek.indexOf(day) >= 0) {
// more cod goes here
window.location = "schedule.php";
} else {
window.location.href = window.location.href;
}
}