为什么我收到错误“Uncaught ReferenceError:增量未定义”

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

代码看起来不错,但仍然收到添加事件处理程序的错误



document.addEventListener('DOMContentLoaded', function() {
    
    let count = 0
    let countEl = document.getElementById("count-el")
    function increment() {
        count = count + 1
        countEl.innerText=count;
        // set countEl's innerText to the count
    }
    increment()
countEl.addEventListener("click", increment);
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./index.js"></script>
    <link rel="stylesheet" href="./index.css">
</head>
<body>
    <h1>People entered:</h1>
    <h2 id="count-el">0</h2>
    <button id="increment-btn" onclick="increment()">INCREMENT</button>
</body>
</html>

请检查代码,错误显示此行 INCRMENT 专门针对该行中的“INCRMENT”

javascript html event-handling undefined
1个回答
0
投票

函数

increment
定义在事件监听器内部。因此在事件侦听器之外无法访问它。因此,您需要在事件侦听器之外定义函数才能访问它。您可以将
countEl.addEventListener("click", increment)
保留在您的
DOMContentLoaded
事件中,这样就可以正常工作。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- <script src="./index.js"></script>
    <link rel="stylesheet" href="./index.css"> -->
</head>

<body>
    <h1>People entered:</h1>
    <h2 id="count-el">0</h2>
    <button id="increment-btn" onclick="increment()">INCREMENT</button>
    <script>
        let count = 0;
        let countEl = document.getElementById("count-el");

        function increment() {
            count = count + 1;
            countEl.innerText = count;
            // set countEl's innerText to the count
        }
        increment();

        document.addEventListener('DOMContentLoaded', function() {
            countEl.addEventListener("click", increment);
        });
    </script>
</body>

</html>

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