使用if语句的条件循环

时间:2014-08-27 12:11:08

标签: javascript prompt

我正在学习一些基本的javascript,并希望学习如何在满足某些条件时返回到方法的开头。

在这种情况下,用户必须在提示中输入一个字符才能继续进行“您输入的字符是”字符串的语句。我想实现一个循环,如果没有输入任何内容,则将程序发送回方法的开头。到目前为止,我有以下内容:

<script class="promptwindow">            
        var x
        x = prompt("Please type a character in the box and click OK", "")

        if (x = null)
            {****}

        document.write("The character you typed was ", x)    
</script>

我不确定在****括号中使用什么,我需要类似goto的内容。

编辑:是的,应该是==。我会把错误留在那里,以便评论有意义。

2 个答案:

答案 0 :(得分:3)

要返回功能的开头,只需再次调用它:

<script type="text/javascript">
   ( function myFunction() {
        var x;
        x = prompt("Please type a character in the box and click OK", "")
        if (x === null)
            myFunction();
        document.write("The character you typed was ", x);
    })();
</script>

document.write()的位置保持忠诚,当x不再为空时,所有堆叠的document.write("The character you typed was ", x);都将被执行

您也可以使用循环...

<script type="text/javascript">
    function myFunction() {
        var x = null;
        while(x === null || x === ""){
            x = prompt("Please type a character in the box and click OK", "")
        }
        document.write("The character you typed was ", x);
    }
</script>

答案 1 :(得分:1)

<script type = "text/JavaScript">
    function UserInput(_callback_)
    {
        var value = "";
        do
        {
            value = prompt("Please type a sentence in the box and click OK", "");
        }
        while(value === "");

        _callback_(value);
    }

    UserInput(function(text){
        document.write("The sentence you typed was { " + text + " }");
    });
</script>

http://jsfiddle.net/dqda8Lgk/

我希望它会对你有所帮助:)。