我对此有点新意,但我正在尝试编写一些javascript代码并遇到一些麻烦。
我有以下代码并反复检查过,无法找到问题。我通过jsfiddle运行它,我无法弄清楚我哪里出错了。
var question = prompt('Who shot Abraham Lincoln?');
if (question == 'john wilkes booth' || question == 'John Booth' || question == 'John Wilkes Booth') {
alert("That\'s Right!");
window.location.href = 'q2.html';
} else {
alert('Sorry, that\'s not right.');
alert('Please try again');
history.refresh();
}
答案 0 :(得分:0)
这是因为行3
和5
中的分号会起作用:
var question = prompt('Who shot Abraham Lincoln?');
if (question == 'john wilkes booth' || question == 'John Booth' || question ==
'John Wilkes Booth') {
alert("That\'s Right!"); window.location.href = 'q2.html';
} else
{
alert("Sorry, that\'s not right.");
alert('Please try again');
history.refresh();
}
答案 1 :(得分:0)
答案 2 :(得分:0)
您可以使用开关/案例:
var question = prompt('Who shot Abraham Lincoln?');
switch (question) {
case 'john wilkes booth':
case 'John Booth':
case 'John Wilkes Booth':
alert("That\'s Right!"); window.location.href = 'q2.html'; break;
default:
alert("Sorry, that\'s not right.");
alert('Please try again');
history.refresh();
break;
}
或者更好,我认为:
var question = prompt('Who shot Abraham Lincoln?');
if (new RegExp("john( wilkes)? booth", "gi").test(question))
{
alert("That\'s Right!"); window.location.href = 'q2.html';
}
else
{
alert("Sorry, that\'s not right.");
alert('Please try again');
history.refresh();
}