如果发生无效输入,如何使函数返回到某个位置?

时间:2013-06-23 14:13:28

标签: javascript error-handling

我有一个功能

function Choice(options) {
wait()
    function wait(){ // only proceed after a selection is made;
        selection = parseInt(selectedchoice);

        if (selection < 1){

            setTimeout(wait,1000);

            console.log("Not chosen yet");

            selection = parseInt(selectedchoice);

        } 
        else if (selection == 1 || selection == 2){

            // Finding what the user selected
            for (var i in options.choices) {
                m++
                if (m === selection){
                    //console.log("PICK IS " + i);
                    pick = i;
                    break
                }
            }
            console.log(options.choices[pick].condition)
            if (selection >= options.choices.length || selection <= 0 || options.choices[pick].condition === false ) {
                selection = 0;
                //Choice(options);
                console.log("Invalid selection");
//USE MAGIC HERE


            }
            else {
                   console.log("Valid selection");
            }
        }
    }
}

如果用户选择了无效的选择,他应该被告知这一点,然后再回头再次选择。显然再次调用函数Choice(选项),即使将选择重置为0后,也会导致无限递归。与throw相同(虽然我不知道如何正确使用它们)。

问题是:如果发生错误,如何使程序再次执行函数Choice()?

2 个答案:

答案 0 :(得分:1)

if更改为while

这样做。虽然没有选择,但代码仍保留在此块上,并且仅在用户进行选择时才会继续

function Choice(options) {
wait()
 function wait() { // only proceed after a selection is made;
    selection = parseInt(selectedchoice);
    while (selection !== 1 || selection !== 2 ) {

        selection = parseInt(selectedchoice);

    }

    // Finding what the user selected
    for (var i in options.choices) {
        m++
        if (m === selection) {
            //console.log("PICK IS " + i);
            pick = i;
            break
        }
        console.log(options.choices[pick].condition)
        if (selection >= options.choices.length || selection <= 0 || options.choices[pick].condition === false) {
            selection = 0;
            //Choice(options);
            console.log("Invalid selection");
            //USE MAGIC HERE
        } else {
            console.log("Valid selection");
        }
    }
}

答案 1 :(得分:0)

我认为你解决这个问题的方法是错误的。你不应该使用setTimeout来“观察”价值变化;相反,你应该让你的逻辑由事件驱动。

在此特定情况下,您希望将change [doc]事件处理程序附加到select元素。每当调用事件处理程序时,您都会确定select元素的值已更改,然后您可以相应地执行针对用户选择的操作。例如,

HTML:

<select id="select" onchange="onSelectChange()">
    <option value="0">Please choose...</option>
    <option value="1">Value 1</option>
    <option value="2">Value 2</option>
</select>

JS:

function onSelectChange() {
    var selection = document.getElementById('select').value;

    if (/* selection is valid */) {
        // do whatever you need to do for a vaild selection
    } else {
        // selection is invalid, you want to notify user invalid
        // selection by using "alert" or something like that, and
        // you're DONE!
    }
}

这样,如果选择无效,用户可以再次选择,一旦用户做出不同的选择,您的处理程序再次运行。