javascript错误'函数未定义'使用html onclick

javascript error 'function not defined' with html onclick

本文关键字:html onclick 使用 未定义 javascript 函数 错误      更新时间:2023-09-26

目标是当有人单击按钮元素时,会触发closeModal()函数,并将display css属性更改为'none'但我一直收到一个错误,即onclick中的函数集没有定义。javascript位于文件中的html上方。

代码如下。

Javascript

function closeModal() {
    var modal = document.getElementById('modal');
    $( modal ).css('display', 'none');
  }

HTML

<div id="modal" style="display:block;">
    <button onclick="closeModal();" id="begin">Let's get started!</button>
</div>

在不使用JQuery的情况下尝试更好、更干净的代码

HTML:

<div id="modal" style="display:block;">
     <button id="begin">Let's get started!</button>
</div>

JavaScript:

window.onload = function(){
    var btn = document.getElementById("begin");
    var modal = document.getElementById("modal");
    btn.onclick = function () {
         modal.style.display = "none";
    }
}

无论在哪里写剧本
祝好运