簡體   English   中英

在這部分javascript中使用onclick的正確方法是什么?

[英]what is the correct way to use onclick in this part of javascript?

所以我正在用JavaScript開發一個簡單的游戲來練習我的技能(是的,我是js的初學者)。

我要在此代碼中實現的目標是,共有9個按鈕,這些按鈕將隨機變為紅色,然后在1秒后恢復正常,當用戶單擊紅色按鈕時,游戲得分+1,否則什么也沒有發生。

所以我想出了這樣的代碼:

問題是,當我在代碼中添加onclick時,當按鈕變為紅色時,gameScore會自動加一,我不確定我做錯了哪一部分,有人可以幫幫我嗎? 我已經在這個問題上停留了一天...

片段:

 var gameScore = 0; function start() { gameTime(); //random number var popTime = Math.random() * 200 + 800; setInterval("ratPop()", popTime); console.log(popTime); }; //rat pop out function ratPop() { var ratNumber = Math.floor(Math.random() * 9); var rats = document.getElementsByClassName('hitArea'); rats[ratNumber].style.backgroundColor = 'red'; rats[ratNumber].onclick = pointsCount(); // this is the problem setTimeout( function goBack() { rats[ratNumber].style.backgroundColor = 'white'; }, 1000 ); }; //timer function gameTime() { var number = document.getElementById('timer'); var count = 60; number.innerHTML = count; var colock = null; colock = setInterval(function() { if (count > 0) { count = count - 1; number.innerHTML = count; } else { clearInterval(colock); } }, 1000); } //score function pointsCount() { var score = document.getElementById('score'); gameScore = gameScore + 1; score.innerHTML = gameScore; }; 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial- scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="./style.css"> <title>Document</title> </head> <body> <div id = 'playGround'> <ul id='rats'> <li><button type="button" class = 'hitArea' id = 'rat0'>rat0</button></li> <li><button type="button" class = 'hitArea' id = 'rat1'>rat1</button></li> <li><button type="button" class = 'hitArea' id = 'rat2'>rat2</button></li> <li><button type="button" class = 'hitArea' id = 'rat3'>rat3</button></li> <li><button type="button" class = 'hitArea' id = 'rat4'>rat4</button></li> <li><button type="button" class = 'hitArea' id = 'rat5'>rat5</button></li> <li><button type="button" class = 'hitArea' id = 'rat6'>rat6</button></li> <li><button type="button" class = 'hitArea' id = 'rat7'>rat7</button></li> <li><button type="button" class = 'hitArea' id = 'rat8'>rat8</button></li> </ul> </div> </div> <div id = 'controlPanel'> <button onclick= "start()">GameStart!</button> <button>GameStop</button> <button>GameOver</button> </div> <div> <h1>time:<span id='timer'>60</span></h1> </div> <div id = 'scoreConter'> <h1>score:<span id='score'>0</span></h1> </div> <script src="./script.js"></script> </body> </html> 

rats[ratNumber].onclick = pointsCount; //here

同樣,您需要在“ onclick”變回白色后將其刪除。

rats[ratNumber].removeAttribute("onclick");

您應該將代碼更改為此:

rats[ratNumber].onclick = function() {
    pointsCount();
}

要么:

rats[ratNumber].addEventListener("click", pointsCount);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM