首先,这是我的代码。
.winner {
color: green;
}
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>JS practice 2</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1><span id="p1Span">0</span> to <span id="p2Span">0</span></h1>
<p class="until">Playing to: </p>
<input type="number">
<button class="playerOne">Player One</button>
<button class="playerTwo">Player Two</button>
<button class="reset">Reset</button>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
max
因此,如您所见,我的p1Display和p2Display应该变成绿色。 问题是,他们没有这样做,而他们却以5分的优势选拔了班级冠军。为什么当它具有将其变成绿色的类时却没有变成绿色?
答案 0 :(得分:3)
您正在通过每次更改span
的内容来擦除h1
。无需这样做,因为您已经在更改span
的内容。所以你必须删除它:
header.textContent = (p1Score + " to " + p2Score);
var p1 = document.querySelector(".playerOne");
var p2 = document.querySelector(".playerTwo");
var p1Display = document.querySelector("#p1Span");
var p2Display = document.querySelector("#p2Span");
var header = document.querySelector("h1");
var reset = document.querySelector(".reset");
//var input = document.getElementsByTagName("input");
var until = document.getElementsByClassName(".until");
var p1Score = 0;
var p2Score = 0;
var gameOver = false;
var max = 5;
p1.addEventListener("click", function() {
if (!gameOver) {
p1Score++;
p1Display.textContent = p1Score;
}
if (p1Score === max) {
p1Display.classList.add("winner");
gameOver = true;
}
});
p2.addEventListener("click", function() {
if (!gameOver) {
p2Score++;
p2Display.textContent = p2Score;
}
if (p2Score === max) {
p2Display.classList.add("winner");
gameOver = true;
}
});
reset.addEventListener("click", function() {
gameOver = false;
p1Score = 0;
p2Score = 0;
p1Display.classList.remove("winner");
p2Display.classList.remove("winner");
});
.winner {
color: green;
}
<h1><span id="p1Span">0</span> to <span id="p2Span">0</span></h1>
<p class="until">Playing to: </p>
<input type="number">
<button class="playerOne">Player One</button>
<button class="playerTwo">Player Two</button>
<button class="reset">Reset</button>
答案 1 :(得分:-1)
您必须在所有功能中删除此代码:
header.textContent =(p1Score +“到” + p2Score);
此外,您还应该从重置功能中删除同一行,并更新p1Display.textContent和p2Display.textContent以使该功能正常工作。
reset.addEventListener("click", function () {
gameOver = false;
p1Score = 0;
p2Score = 0;
p1Display.textContent = p1Score;
p2Display.textContent = p2Score;
p1Display.classList.remove("winner");
p2Display.classList.remove("winner");
//header.textContent = (p1Score + " to " + p2Score);
});
致谢!