3 回答
TA贡献1895条经验 获得超3个赞
hitElement.innerHTML = hits % 5
var hits = 0;
var hitElement = document.querySelector(".hits");
document.body.onkeyup = function (e) {
if (e.keyCode == 32) {
addHit();
}
};
var addHit = function () {
hits++;
renderHits();
};
var renderHits = function () {
hitElement.innerHTML = hits %= 5;
console.log({hits});
};
var resetHits = function () {
hits = 0;
renderHits();
};
<span class="hits"> 0 </span>
<button onclick="resetHits()" class="tryagain">RESTART</button>
更新:根据@tarkh 的观点,更新为hitElement.innerHTML = hits %= 5;
,因此该变量值也是最新的。
TA贡献1812条经验 获得超5个赞
在这里我修改你的代码
<!DOCTYPE html>
<html>
<body>
<span class="hits"> 0 </span>
<button onclick="resetHits()" class="tryagain">RESTART</button>
<script>
var hits = 0;
var hitElement = document.querySelector('.hits');
document.body.onkeyup = function(e) {
if(e.keyCode == 32) {
// ADD counter check here
if(hits === 4 + 1) { // Add +1 if you need do reset after 4 displayed
// Do what you want
resetHits();
}
// Then it depends on your logic,
// if you don't need to cycle counter immediately,
// add rest to else condition like so
else { addHit(); }
}
}
var addHit = function() {hits++; renderHits()}
var renderHits = function() {hitElement.innerHTML = hits}
var resetHits = function() {hits = 0; renderHits()}
</script>
</body>
</html>
TA贡献1852条经验 获得超1个赞
试试这个。4 不会显示。它将自动重置为 0。
<!DOCTYPE html>
<html>
<body>
<span class="hits"> 0 </span>
<button onclick="resetHits()" class="tryagain">RESTART</button>
<script>
var hits = 0;
var hitElement = document.querySelector('.hits');
document.body.onkeyup = function(e) {
if(e.keyCode == 32) {addHit()}}
var addHit = function() {
hits++;
if (hits === 4) {
resetHits();
}
renderHits()
}
var renderHits = function() {hitElement.innerHTML = hits}
var resetHits = function() {hits = 0; renderHits()}
</script>
</body>
</html>
添加回答
举报