我正在创建一个简单的游戏,修改我的HTML并跟踪我正在键入的键。当我有一定的分数时,我输入的键应该从我的段落元素中清除,但它不会被清除。我正在使用innerHTML并将其设置为等于空字符串。它永远不会清除。
var losses = 0;
var guessesLeft = 10;
var guesses = guessesLeft;
document.onkeypress = function(event) {
var userChoice = event.key;
console.log("guesses" + guesses);
if (guesses === guessesLeft) {
console.log("Will this work" + userChoice);
document.getElementById('guess').innerHtml = "";
var newContent = document.createTextNode(userChoice);
} else {
var newContent = document.createTextNode(', ' + userChoice);
}
console.log("newContent" + newContent[0]);
var newEl = document.createElement('span').appendChild(newContent);
document.getElementById('guess').appendChild(newEl);
if (guesses === 0) {
losses++;
document.getElementById('losses').innerHTML = ("Losses: " + losses);
guesses = guessesLeft;
}
};
<div class="container">
<div class="row">
<div class="col-lg-12 jumbotron">
<h1> The Psychic Game </h1>
</div>
</div>
<div class="row">
<div class="col-lg-4 one">
</div>
<div class="col-le-4 content">
<p> Guess what letter I'm thinking of? </p>
<p id="wins"> Wins: </p>
<p id="losses"> Losses: </p>
<p id="left"> Guesses Left: </p>
<div>
<p> Your guesses so far: <span id="guess"> </span></p>
</div>
</div>
</div>
答案 0 :(得分:0)
以下是修改后的代码。所有我改变的是innerHtml到innerText并添加了猜测 - 在if(猜测=== 0)条件的else部分。
我希望这会有所帮助。
var losses = 0;
var guessesLeft = 10;
var guesses = guessesLeft;
document.onkeypress = function(event) {
var userChoice = event.key;
console.log("guesses" + guesses);
if (guesses === guessesLeft) {
console.log("Will this work" + userChoice);
document.getElementById('guess').innerText = "";
var newContent = document.createTextNode(userChoice);
} else {
var newContent = document.createTextNode(', ' + userChoice);
}
console.log("newContent" + newContent[0]);
var newEl = document.createElement('span').appendChild(newContent);
document.getElementById('guess').appendChild(newEl);
if (guesses === 0) {
losses++;
document.getElementById('losses').innerHTML = ("Losses: " + losses);
guesses = guessesLeft;
}
else
guesses--;
};
<div class="container">
<div class="row">
<div class="col-lg-12 jumbotron">
<h1> The Psychic Game </h1>
</div>
</div>
<div class="row">
<div class="col-lg-4 one">
</div>
<div class="col-le-4 content">
<p> Guess what letter I'm thinking of? </p>
<p id="wins"> Wins: </p>
<p id="losses"> Losses: </p>
<p id="left"> Guesses Left: </p>
<div>
<p> Your guesses so far: <span id="guess"> </span></p>
</div>
</div>
</div>