2 回答
TA貢獻1805條經驗 獲得超10個贊
聽起來好像text正在被插入到 DOM 中,并且用戶必須在邏輯繼續之前輸入另一個輸入。這種附加值的輸入是異步的。表達鏈式異步代碼流的最清晰方法是使用async/ await:您可以創建一個返回 Promise 的函數,該 Promise 在用戶按下按鈕時解析。每當你想實現詢問用戶的邏輯時,調用它和awaitPromise。
switch非常丑陋和冗長,考慮使用普通的if/else語句。
還要考慮小寫輸入文本,它會讓用戶更輕松。
避免內聯處理程序也很好,它們有太多問題。改為使用 Javascript 附加偵聽器。
const button = document.querySelector('button');
const input = document.querySelector('input');
const nextInput = () => new Promise((resolve) => {
button.onclick = () => {
resolve(input.value.toLowerCase());
};
});
const summary = document.querySelector('div');
const display = text => summary.innerHTML = text;
const main = async () => {
const textInput = await nextInput();
if (textInput === 'help1') {
display("[Page 1 of 2. Type 'Help2' for page 2] Commands you can use: <ul><li>South</li><li>North</li><li>East</li><li>West</li><li>North Again</li><li>South again</li>");
} else if (textInput === 'help2') {
display("[Page 2 of 2] Commands you can use: <li>North One More</li><li>East Once More</li><li>West Once More</li><li>South Once More</li><li>East Again</li><li>West Again</li>");
} else if (textInput === 'south') {
display("You went to the city; street 2. Do you want to explore?");
const exploring = await nextInput();
if (exploring === 'yes') {
display('Exploring');
} else {
display('Not exploring');
}
}
// go back to beginning state
main();
};
main();
<input type="text" placeholder="Type 'Help1' for actions">
<button>Confirm</button>
<div></div>
TA貢獻1921條經驗 獲得超9個贊
您可以嵌套另一個switch...case. 您只需要確保為答案分配了一個值,或者使用諸如 window.prompt 之類的東西來獲得答案。
例如:
switch (textInput) {
case "Help1":
text = "[Page 1 of 2. Type 'Help2' for page 2] Commands you can use: <ul><li>South</li><li>North</li><li>East</li><li>West</li><li>North Again</li><li>South again</li>""
break;
case "Help2":
text = "[Page 2 of 2] Commands you can use: <li>North One More</li><li>East Once More</li><li>West Once More</li><li>South Once More</li><li>East Again</li><li>West Again</li>";
break;
case "South":
switch(window.prompt("Do you want to explore?")){
case "yes":
console.log("user wants to explore")
break;
case "no":
console.log("user does not want to explor")
break;
}
break
}
添加回答
舉報
