首页 > 解决方案 > 我不断收到错误 Uncaught ReferenceError: nothingButton is not defined

问题描述

所以我不断收到这个错误 nothingButton is not defined。但我定义了它。有人知道发生了什么吗?

JavaScript:

    function nothingButton() {
    $("#button-nothing").on('click', function() {
        $(this).prop('disabled', true);
        const p = document.createElement('p');
        p.innerText = "Well, except for this";
        document.querySelector('#button').appendChild(p);
    })
}

HTML:

<div id="button">
<button id="button-nothing" onclick='nothingButton()'>This button does nothing</button>
</div>

我的 html 文件中也有 javascript 文件源。

标签: javascripthtml

解决方案


嗯,上面的代码其实没问题。

它可能是您的代码中的其他内容,或者只是一些排版错误。

除了您可能会收到 2 条“好吧,除了这个”消息之外,因为每次单击按钮时,它都会附加另一个onclick 侦听器。

这是我为您重新创建的内容:

<html>

<head>
    <!-- Use jquery from cdnjs here -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>

<body>
    <div id="button">
        <button id="button-nothing">This button does nothing</button>
    </div>
    <script>
        function nothingButton() {
            $("#button-nothing").on('click', function () {
                $(this).prop('disabled', true);
                const p = document.createElement('p');
                p.innerText = "Well, except for this";
                document.querySelector('#button').appendChild(p);
            });
        }

        // Attach the event listener once.
        nothingButton();
    </script>
</body>

</html>

初始状态:

初始按钮状态

按钮点击状态:

收到点击后的按钮状态


推荐阅读