我将如何在小部分中暂停我的代码,而我的if和else语句不起作用

时间:2011-11-27 06:08:19

标签: javascript

我希望我的代码停止/停止/中断我放置return;的位置,我希望它停止,我尝试使用break如果有人可以帮助我,我会感激,我是对Javascript来说很新,所以如果我第一次没有把一切都弄好的话,不要生气:D anyhelp会非常感激。

function InitAll() {
    var name = prompt("What is your name?", "");
    document.write("Hello, " + name + " this is a little Javascript Activity!");
    var PromptAnswer = prompt("So, " + name + " do you like to play Soccer?", "");
    if (PromptAnswer == "yes" || "Yes" || "Yes!" || "yes!" || "yeah" || "yeah!" || "Yeah!") {
        document.write("Cool, that's awesome, i play Soccer too!");
        var PromptAnswer2 = prompt("Well, even some people play Soccer and don't like it, do you like soccer?", "");
        if (PromptAnswer2 == "yes" || "Yes" || "Yes!" || "yes!" || "yeah" || "yeah!" || "Yeah!") {
            document.write("Yeah, its pretty fun.");
        }
        if (PromptAnswer2 == "") {
            return;
        }
        else {
            document.write("Well, that's really too bad, but i guess if you don't like it, you dont like it. :D");
        }
    }
    else {
        var PromptAnswer3 = prompt("Well, what sports do you like to play?", "");
        if (PromptAnswer3 == "football" || "Football") {
            document.write("Haha yeah, football is pretty awesome, even though i'm a Javascript Script, my Creator can throw football pretty well. :D");
        }
        else {
            document.write(PromptAnswer3 + " is pretty cool.");
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您的代码中存在多个问题。

提示函数可以返回null,因此您可能想要更改此内容:

    if (PromptAnswer2 == "") {
        return;

到此:

    if (!PromptAnswer2) {
        return;
    }

return语句将完成该函数的执行,将控制权返回给称为函数的任何函数。

这会检查PromptAnswer2 null""undefined以及其他一些内容。

其次,这样的陈述:

if (PromptAnswer == "yes" || "Yes" || "Yes!" || "yes!" || "yeah" || "yeah!" || "Yeah!")

必须写成这样:

if (PromptAnswer == "yes" || PromptAnswer == "Yes" || PromptAnswer == "Yes!" || PromptAnswer == "yes!" || PromptAnswer == "yeah" || PromptAnswer == "yeah!" || PromptAnswer == "Yeah!")

或者甚至可能更好地删除不同的案例可能性:

PromptAnswer = PromptAnswer.toLowerCase();
if (PromptAnswer == "yes" || PromptAnswer == "yes!" || PromptAnswer == "yeah" || PromptAnswer == "yeah!")

或使用正则表达式:

if (PromptAnswer.match(/^(yes|yeah)!?$/i))

第三,您可能想知道满载文档上的document.write()将清除当前文档并开始编写新文档。通常不是在事件处理javascript中想要做的事情。