我不断收到错误 Uncaught ReferenceError: nothingButton is not defined

时间:2021-05-30 02:49:10

标签: javascript html

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

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 文件源。

1 个答案:

答案 0 :(得分:0)

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

这可能是您的代码中的其他问题,或者只是一些排版错误。

除了您可能会收到 2 个“好吧,除了这个”消息之外,因为每次您点击按钮时,附加另一个点击监听器

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

<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>

初始状态:

Initial button state

按钮点击状态:

Button state after click received