0

我有一个功能

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(options),即使将选择重置为 0,也会导致无限递归。与 throw 相同(尽管我不知道如何正确使用它们)。

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

4

2 回答 2

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");
        }
    }
}
于 2013-06-23T14:20:38.793 回答
0

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

在这个特定的情况下,您希望将change[ doc ] 事件处理程序附加到您的 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!
    }
}

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

于 2013-06-23T14:56:17.010 回答