JavaScript 无法与独立文件中的 HTML 配合,它们在同一个 HTML 文件中工作

问题描述 投票:0回答:1

所以我做了一个简单的点击按钮的游戏,计时器设置为 5 秒,每次点击计数器都会增加(一切都在同一个文件 [index.html] 中运行)。每当我尝试将代码放入独立文件中,例如 js.js 和 index.html,锚点为:

<script src="js.js"></script>

它不起作用,并且显示错误,例如: Uncaught TypeError TypeError: Cannot read properties of null (reading 'addEventListener')

这是 JS 和 HTML 代码:

// Global variables
const clickButton = document.getElementById('clickButton');
const counterElement = document.getElementById('counter');

// Counter
let counter = 0;
clickButton.addEventListener('click', () => {
  counter++;
  counterElement.textContent = counter;
  moveButtonRandomly();
});

// Timer
let timeLeft = 5;
let timerElement = document.getElementById('timer');
let timer;

function countdown() {
    if (timeLeft > 0) {
        timeLeft--;
        timerElement.textContent = timeLeft;
    } else {
        clearInterval(timer);
        alert('Game Over! You lose!');
    }
};

function startTimer() {
    timer = setInterval(countdown, 1000);
}

function resetTimer() {
    clearInterval(timer);
    timeLeft = 5;
    timerElement.textContent = timeLeft;
}

document.getElementById('startofthegame').addEventListener('click', startTimer);
document.getElementById('clickButton').addEventListener('click', startTimer);


// Random button position
function moveButtonRandomly() {
  const randomX = Math.random() * (window.innerWidth - clickButton.offsetWidth);
  const randomY = Math.random() * (window.innerHeight - clickButton.offsetHeight);
  clickButton.style.left = randomX + 'px';
  clickButton.style.top = randomY + 'px';
}

// Start of the actual game after clicking "START!" button
document.getElementById("startofthegame").addEventListener("click", moveButtonRandomly);
const start = document.getElementById("startofthegame");
start.addEventListener("click", hidden)
function hidden() {
 var button = document.querySelector(".hidden");
button.classList.remove("hidden")
var button2 = document.querySelector(".text")
button2.setAttribute("style", "display: none;")
}

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <script src="js.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Position Button</title>
</head>
<body>
<div class="text">
  <p>Welcome to simple clicking game!</p>
<button id="startofthegame" class="start">Start!</button>
</div>
<div class="hidden">
<button id="clickButton" onclick="resetTimer()">Click me</button>
<p>Counter: <span id="counter">0</span></p>
<p>Time left: <span id="timer">5</span> seconds</p>
</div>
</script>

</body>
</html>

我尝试使用 DOMContentLoading 加载页面,但仍然不起作用,尝试重做一些代码行,仍然失败,整个页面都损坏了。我真的不知道如何解决这个问题。

(抱歉,如果我的代码是意大利面条式的,你们中的一些人可以减少 50% 的行数,但我是一个初学者,想自己尝试一些东西)

javascript html css
1个回答
0
投票

错误的原因是因为代码在主体创建之前就被执行了。所以

clickButton
还不存在。

您只需在正确的时间运行代码,即 DOM 内容加载完成后。您可以通过在文档的

DOMContentLoaded
事件上使用 eventHandler 来完成此操作。

document.addEventListener("DOMContentLoaded", (event) => {
    // Insert JS code here
});

奇怪的是,即使 javascript 直接存在于您的页面中,这也应该是需要的。我假设javascript之前没有放在头部而是放在主体的末尾?将脚本放在正文的末尾是常见的做法。

© www.soinside.com 2019 - 2024. All rights reserved.