【问题标题】:Javascript - Can't get my program to run - Loop never endsJavascript - 无法让我的程序运行 - 循环永远不会结束
【发布时间】:2015-12-07 16:23:53
【问题描述】:

我的程序运行不正确。它应该提示您输入您的姓名并存储它 - 然后要求您选择选项 1,2 或 3(退出并返回选择) - do-while 循环。然后我的函数不会被调用,例如如果用户类型 1 则调用 Opt1,用户类型 2 则调用 Opt2。如果有人能提供帮助,那真是太棒了。

<html>
<head>
    <script type='text/javascript'>

        var me;
        function Menu () {
            var choice;
            me = prompt("Who are you?"," ") ;

            do {
                prompt("Choose option 1, 2 or 3" + choice);
                choice = parseInt(choice);

                switch (choice) {
                    case 1: {
                        Opt1();
                        break;
                    }
                    case 2: {
                        Opt2();
                        break;
                    }
                    case 3: {
                        alert("All done");
                        break;
                    }
                } //end of switch
            } //end of do-while

            while (choice != 3); {
                break;
            }

        } //end Menu

        function Opt1()
        {
            var user;
            alert(me + "This is Option 1") ;
            user = prompt("Enter first and last name");
            alert('Welcome ' + create_name(user));
            create_name(user);
        }

        function Opt2()
        {
            alert(me + 'This is Option 2' + me);
        }

        function create_name(username) { //string manipulation
            var string1 = username.substr(0,1);
            alert("Hello" + string1);
            var len = username.length;
            alert("the number of letters in your name is " + len);
            var pos = username.indexOf(" ");

            alert("the space is located at position " + pos);
            var string2 = username.substr(pos+1);
            username = string1+string2;

            alert ('Welcome ' + username);
        }

    </script>
</head>
<body>
    <h1> Software Program</h1>
    <input type="button" value="Menu" onclick="Menu();" />
</body>
</html>

【问题讨论】:

  • 你应该先学会缩进你的代码......它很难读。
  • while (choice != 3); { break;} 应该是while (choice != 3);

标签: javascript function switch-statement parameter-passing case


【解决方案1】:

@CodeiSir 是对的,但真正的问题是您没有收集用户输入的值。

改变这个

                prompt("Choose option 1, 2 or 3" + choice);

用这个:

                choice = prompt("Choose option 1, 2 or 3");

问候

【讨论】:

    猜你喜欢
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多