Javascript,如果继续其他的话

beb*_*666 1 javascript

出于某种原因,在if之后,它继续到其他地方,除了把你带到另一个地方的ifs,这里是我目前的代码

<script type="text/javascript">
    function whatname(button) {
        var post = prompt("Name?", "Visitor")
        if(post == "Nick"){
            alert("Hi Nick")
            window.location = "index.html"
        }
        if(post == "Visitor"){
            alert("Welcome Visitor")
            window.location = "index.html"
        }
        if(post == ""){
            alert("Please Enter Name")
        }
        if(post == null){
            alert("Closing")
        }
        if(post == "show me a secret"){
            window.location = "secret.html"
        }
        if(post == "Greg"){
            alert("Test")
        }
        if(post == "greg"){
            alert("Test 1")
        }
        else{
            alert("Welcome " + post + ", Have Fun!")
            window.location = "index.html"
        }
    }
</script>
Run Code Online (Sandbox Code Playgroud)

在if发生后,它继续其他,就像我说点击取消(这将是null)它会说,"关闭"但是比另一个弹出窗口会出现并且会说,"欢迎空闲,玩得开心!" 我不会把它带到其他地方,我不知道什么是错的,如果你能提供帮助,那就太好了.

Dav*_*und 8

使用else if而不是if

if(condition 1) {
} else if(condition 2) {
} else {
}
Run Code Online (Sandbox Code Playgroud)

现在发生的事情是它首先检查是否post是"尼克".无论是否是,它都会继续检查是否post是"访客".这当然不是你想要的.如果发现第一个测试是假的,您只想执行第二个测试.

如上所述,只有最后一个if声明才有else.您将看到"欢迎,有乐趣" -消息时post是什么,但greg.