为什么'机会 - '不能像我想的那样工作?我只想减去1.它减去了单词的长度。即使字母匹配,它也会减去。我在减法后尝试了console.log“机会”并记录: 6, 5, 4, 3, 2, 1, 0 然后,每次提交表单时,它会继续减去“单词”的长度。
function createBoxes(word) {
var bigDiv = document.getElementsByClassName('game')[0];
for (var i = 0; i < word.length; i++) {
var newDiv = document.createElement('div');
bigDiv.appendChild(newDiv)
};
};
var selectedWord = 'Romania'.toLowerCase();
createBoxes(selectedWord);
window.onload = function() {
var chances = document.querySelector('#chances').innerText = selectedWord.length
var form = document.querySelector('.form');
form.addEventListener('submit', function(evt) {
evt.preventDefault();
// You have to enter one letter
var selectedLetter = document.querySelector('#selectText').value;
if (selectedLetter.length > 1) {
alert('You have to enter one letter')
}
// Check if the letter match
var allNewDivs = document.querySelectorAll('.game div');
for (var i = 0; i < allNewDivs.length; i++) {
if (selectedWord[i] === selectedLetter) {
allNewDivs[i].innerText = selectedLetter.toUpperCase();
} else {
chances--
}
};
});
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hangman</title>
<style media="screen">
.game > div {
width: 20px;
height: 20px;
position: relative;
display: inline-block;
border-bottom: 1px solid black;
margin-right: 3px;
}
</style>
</head>
<body>
<div class="count">
<h3>Chances remained: <strong id="chances"></strong></h3>
</div>
<div class="game"></div>
<form class="form">
<input id='selectText' type="text">
<input type="submit" value="Select">
</form>
<script src='script.js'></script>
</body>
</html>
答案 0 :(得分:0)
function createBoxes(word) {
var bigDiv = document.getElementsByClassName('game')[0];
for (var i = 0; i < word.length; i++) {
var newDiv = document.createElement('div');
bigDiv.appendChild(newDiv)
};
};
var selectedWord = 'Romania'.toLowerCase();
createBoxes(selectedWord);
window.onload = function() {
var chances = document.querySelector('#chances').innerText = selectedWord.length;
var form = document.querySelector('.form');
form.addEventListener('submit', function(evt) {
evt.preventDefault();
// You have to enter one letter
var selectedLetter = document.querySelector('#selectText').value;
if (selectedLetter.length > 1) {
alert('You have to enter one letter')
}
// Check if the letter match
var found = false;
if(chances >0){
var allNewDivs = document.querySelectorAll('.game div');
for (var i = 0; i < allNewDivs.length; i++) {
if (selectedWord[i] === selectedLetter) {
allNewDivs[i].innerText = selectedLetter.toUpperCase();
found = true;
}
};
if(!found){
chances--;
document.querySelector('#chances').innerText = chances;
}
}else{
alert('you have reached the limit');
}
});
}
答案 1 :(得分:0)
因为chance--
位于for
循环内,逐字检查。所以每个字母减少一次