在这里进行基本的DOM操作。一切正常:当任何玩家达到5之类的预定义数字时,目前分数变为绿色并停止进一步增加。然后,当我单击“重置”按钮时,它将重置为“0到0”,但是当我单击任何“播放器”按钮时,它将继续前一个值,而不是从0开始。
/*global prompt,alert,console*/
/*jslint plusplus: true */
var button1 = document.querySelector(".button1");
var button2 = document.querySelector(".button2");
var p1Display = document.querySelector(".p1display");
var p2Display = document.querySelector(".p2display");
var reset = document.querySelector(".reset");
var val1 = 0;
var val2 = 0;
var maxVal = 5;
var gameOver = false;
button1.addEventListener('click', function () {
'use strict';
if (gameOver === false) {
val1++;
if (val1 === maxVal) {
p1Display.classList.add("win");
gameOver = true;
}
p1Display.textContent = val1;
}
});
button2.addEventListener('click', function () {
'use strict';
if (gameOver === false) {
val2++;
if (val2 === maxVal) {
p2Display.classList.add("win");
gameOver = true;
}
p2Display.textContent = val2;
}
});
reset.addEventListener('click', function () {
'use strict';
var val1 = 0;
var val2 = 0;
p1Display.textContent = 0;
p2Display.textContent = 0;
p1Display.classList.remove("win");
p2Display.classList.remove("win");
gameOver = false;
});
.win{
color: green;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Score Keeper</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1><span class="p1display">0</span> to <span class="p2display">0</span></h1>
<h3>Playing To : <span class="maxval">5</span></h3>
<input type="number" class="setVal" min="1">
<button class="button1">Player One</button>
<button class="button2">Player Two</button>
<button class="reset">Reset</button>
<script src="script.js"></script>
</body>
</html>
答案 0 :(得分:2)
重置时不要使用var
:在重置功能中,替换
var val1 = 0;
var val2 = 0;
通过
val1 = 0;
val2 = 0;
val1
和val2
已在外部范围内声明,在较窄范围内重新声明它们只会创建具有相同名称的不同变量(“阴影”):两个变量val1
重置功能内的val2
与功能外的With Me.myCombobox
.SetFocus
.SelStart = 0
.SelLength = 0 ' Nothing selected
End With
With Me.myCombobox
.SetFocus
.SelLength = Len(.Text) ' Content selected
End With
不同。实际上它们从未被使用过,这就是JSLint报告重新声明的原因,而JSHint表示它们是未使用的变量。