我正在尝试制作一个程序,让用户猜测 1 到 100 之间的数字。您会得到 10 次猜测,并且程序应该告诉用户他/她的猜测是否太高或太低,但是直到使用完所有 10 个猜测后,程序才会在文档上写入内容。我该如何解决这个问题?
这是我的代码:
var a = Math.random();
var b = a * (101 - 1) + 1;
var c = Math.floor(b);
document.write(b + "<br>");
document.write(c + "<br>");
var d = 1;
while (gjett != c && d <= 10) {
var gjett = Number(prompt("Gjett på et tall fra 0 til 100"));
if (gjett < c) {
document.write("Tallet er høyere enn " + gjett + ".<br>");
}
if (gjett > c) {
document.write("Tallet er lavere enn " + gjett + ".<br>");
}
d = d + 1;
}
最佳答案
专业提示:don't use document.write
.
现在,您看不到任何内容的原因基本上是浏览器处于 JavaScript 模式或渲染模式。只要某些 JavaScript 正在运行,DOM 就不会被渲染。这样,如果您对 DOM 进行多次更改,浏览器就不会浪费资源来渲染其间的所有小更改。
处理此问题的更好方法是使用按钮和某种输入。
// Wait for the user to click on the button
document.querySelector('button').addEventListener('click', function() {
// Get the value the user put in
var inputEl = document.querySelector('input');
// Make sure it's an integer
var value = parseInt(inputEl.value);
// Get the output element
var outputEl = document.getElementById('output');
// Tell the user what they guessed
outputEl.innerHTML = 'You guessed ' + value;
});
<input type="text" />
<button>Try</button>
<br />
<p id="output"></p>
你可以自己弄清楚猜谜游戏的实际逻辑;)
关于javascript - 初学者 - while 循环中的 document.write,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40116044/