在提示消息中,我要求输入一个数字,我想更新DOM元素(输入),但仅在do时才起作用-结束时,我想在每条提示消息后更新DOM。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Odds and Evens Game</title>
</head>
<body>
<form>
Number: <input type="text" id="number">
<input type="button" onclick="showIt()" value="ShowIt">
</form>
<script>
function showIt(){
var inputval ;
do {
inputval = prompt('Enter a number between 1 and 5 , 999 to exit');
number = parseInt(inputval);
document.getElementById('number').value= number;
}while(number !== 999);
}
</script>
</body>
</html>
答案 0 :(得分:1)
prompt
窗口prevents the user from accessing the rest of the program's interface until the dialog box is closed
。您的while循环会反复调用提示,并再次阻止对用户界面的访问。
使用await,在调用第二个提示之前绘制窗口。
let num = 0;
let ele = document.querySelector('#num');
(async () => {
do {
await getInput()
ele.value = num;
await sleep(0);
} while(num !== 999);
})();
function sleep(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
})
}
function getInput() {
return new Promise(resolve => {
num = Number(prompt("Enter num"));
resolve(num);
});
}
Number: <input type="text" id="num">
答案 1 :(得分:1)
也许我不能完全理解这个问题,因为您的代码确实可以正常工作,除了最后一个999
退出位(在Firefox,Linux上)-因为该代码随后将您的输入更新为999
。为什么您仍然有这个999 to exit
?
以下一些较小的更改和选项:
function showIt(){
var inputval, num;
do {
inputval = prompt('Enter a number between 1 and 5 (inclusive), 999 to exit');
num = parseInt(inputval);
if ((num != NaN) && (num >= 1) && (num <= 5) && (num != 999)) {
document.getElementById('number').value = num;
}
} while (num !== 999);
}
function updateAndExit(e) {
var inputval = prompt('Enter a number between 1 and 5 (inclusive)');
var num = parseInt(inputval);
if ((num != NaN) && (num >= 1) && (num <= 5)) {
this.textContent = num;
}
}
window.onload = function() {
var d = document.getElementById("click-to-udpate");
if (d) {
d.addEventListener("click",updateAndExit,false);
}
}
.fakeInput {
border:1px solid #886;
padding:6px;
background:#ddd;
}
.fakeInput:hover {
border:1px solid #688;
background:#fff;
cursor:pointer
}
Number: <input type="text" disabled="disabled" id="number">
<input type="button" onclick="showIt()" value="ShowIt">
<p>
Different option below:
</p>
<div id="click-to-udpate" class="fakeInput">Click to update</div>