gpt4 book ai didi

javascript - 如果发生无效输入,如何使函数返回到特定位置?

转载 作者:行者123 更新时间:2023-12-03 08:33:19 24 4
gpt4 key购买 nike

我有一个功能

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");
}
}
}
}

如果用户选择了一个无效的选择,则应告知他有关该选择,并向后扔一点以再次选择。显然,即使将选择重置为0后,再次调用函数Choice(options)也会导致无限递归。与throw相同(尽管我不知道如何正确使用它们)。

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

最佳答案

我认为您解决此问题的方法是错误的。您不应该使用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!
}
}

这样,如果选择无效,则用户可以再次选择,一旦用户做出其他选择,处理程序 将再次运行

关于javascript - 如果发生无效输入,如何使函数返回到特定位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17261575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com