我正在做一個有UI的石頭剪刀布的項目。所以,我有四個按鈕,開始游戲,石頭,紙和剪刀。我想如果我點擊開始游戲按鈕,一個警告(& quot請選擇石頭、布或剪刀& quot)會彈出。如果我現在點擊開始游戲。什么都沒發生。我不知道為什么?以下是我的代碼:
- HTML代碼-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Project Rock Paper Scissors</title>
<script src = "javascript.js"> </script>
</head>
<body>
<div class="btn-group">
<button id="startgame"> Start game </button>
<button id="rock"> Rock </button>
<button id="paper"> Paper </button>
<button id="scissor"> Scissor </button>
</div>
</body>
</html>
- Javascript -
const startGame = document.querySelector('#startgame');
if (startGame) {
startGame.addEventListener('click', () => {
alert("Choose Rock, Paper or Scissor");
})
}
const rock = document.querySelector('#rock');
const paper = document.querySelector('#paper');
const scissor = document.querySelector('#scissor');
在您的代碼中,startGame返回null。
方法1 在您的html代碼中,在結尾調用javascript代碼,在關閉& ltbody & gt標簽
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Project Rock Paper Scissors</title>
</head>
<body>
<div class="btn-group">
<button id="startgame"> Start game </button>
<button id="rock"> Rock </button>
<button id="paper"> Paper </button>
<button id="scissor"> Scissor </button>
</div>
<script src = "javascript.js"> </script>
</body>
</html>
方法2 將defer屬性添加到& lt腳本& gt標簽
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Project Rock Paper Scissors</title>
<script src = "javascript.js" defer> </script>
</head>
<body>
<div class="btn-group">
<button id="startgame"> Start game </button>
<button id="rock"> Rock </button>
<button id="paper"> Paper </button>
<button id="scissor"> Scissor </button>
</div>
</body>
</html>
你可以通過這個問題了解更多信息。信用問題提問者和一些回答者。這個答案的部分內容可能是從他們那里得到的啟發。