我这样做的方法是获取html元素,并在封装整个程序的函数(({}中将它们声明为全局常量变量。它有效,但我不确定这是否是一个好的做法。有没有一种方法可以在不使用无所不在的函数(({}的情况下允许元素的可重用性,或者这可以吗?
我的代码:
document.addEventListener('DOMContentLoaded', function() {
//The global const elements from HTML doc
const square = document.getElementsByClassName("square");
const mole = document.getElementsByClassName("mole");
const timeLeft = document.getElementsByClassName("time-left")[0]; //# for id elements
//Initialize score, result, and time
let score = document.getElementsByClassName("score")[0];
let result = 0;
let currentTime = timeLeft.textContent;
//Call countDown function every 1000 milliseconds or 1 second
let timerId = setInterval(countDown, 1000);
function main() {
//Add an event listener for each square called mouseup
for (let i = 0; i < square.length; i++) {
square[i].addEventListener("mouseup", checkHit);
}
moveMole()
}
//Once the event triggers, check if val of current square equals to hitPosition
//If it is, update result and hitPosition
function checkHit(event) {
if (this.id === hitPosition) {
result = result + 1;
score.textContent = result;
hitPosition = null;
}
}
//Move mole to a random square every 1000 milliseconds
function moveMole() {
let timerId = null;
timerId = setInterval(randomSquare, 1000);
}
//Choose a randomSquare to put the mole
function randomSquare() {
//Remove mole from the class name to make sure there isn't any forgotten divs that were used for styling
for (let i = 0; i < square.length; i++) {
square[i].classList.remove("mole");
}
//Math.floor rounds down
//math.random() * 9 uses a position from 1 to 9
let randomPosition = square[Math.floor(Math.random() * 9)];
//Set the mole to the randomPostion
randomPosition.classList.add("mole");
//Assign the id of the randomPositon to hitPosition for comparing later
hitPosition = randomPosition.id;
}
//Counts our timer down
function countDown() {
//Decrement currentTime and show currentTime
currentTime--;
timeLeft.textContent = currentTime;
//If currentTime is 0
//Clear the timer set by the setInterval method
//Stops the execution of randomSquare
//Alert user of final score
//Reset time and result
if (currentTime === 0) {
alert("GAME OVER! Your final score is " + result);
timeLeft.textContent = 30;
currentTime = timeLeft.textContent;
result = 0;
score.textContent = result;
}
}
main();
})
就我而言,代码看起来不错,但一定要看看其他人,看看他们在做什么。