我正在尝试使用某些JavaScript功能获取提交按钮,但似乎无法获得正确的结果。
在加热拉动页面上.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 新手,我不知道出了什么问题,即使我已经在这个地方寻找答案。任何帮助都会很棒。干杯。
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() 方法从当前 URL 重新加载资源。
编辑 2
完整代码
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";
}
}
先做一些解释。
使用 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
在 JavaScript 中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;
}
}