javascript - 由于未捕获类型错误 : Cannot set property 'onclick' of null,无法关闭 Modal

标签 javascript jquery html

当我运行以下代码时,当我单击下拉菜单的“当前子项”选项时,相应的模态框会显示在我的屏幕上,但随后我无法将其关闭,因为我在“

”处收到以下错误
spanModal.onclick = function()

错误是:

userTemplate.js:25 Uncaught TypeError: Cannot set property 'onclick' of null
    at HTMLAnchorElement.<anonymous> (userTemplate.js:25)
    at HTMLAnchorElement.dispatch (jquery-3.2.1.js:5206)
    at HTMLAnchorElement.elemData.handle (jquery-3.2.1.js:5014)

为什么我会收到此错误?

HTML:

<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
              <ul class="nav navbar-nav">
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Children <span class="caret"></span></a>
                      <ul class="dropdown-menu">
                        <li><a href="#" class="menu" id="currentChildren">Current Children</a></li>
                        <li>
                    </ul>  
                </li>
           </ul>
     </div>

<div id="currentChildrenModal" class="modal">
  <div class="modal-content">
    <span class="close" id="currentChildrenModalSpan">&times;</span>
      <p>List of all currently enrolled children. Include option to filter by group.</p>
  </div>
</div>

Javascript:

$(".menu").on("click", function()
{
    var modalFireButton;
    var modalName;
    var spanModal;
    var span;
    //get Id of button cliced
    modalFireButton = $(this).attr('id');

    //set variable for corresponding modal 
    modalName = (modalFireButton + "Modal");

    modalName = document.getElementById(modalName);
    span = (modalName + "Span");

    spanModal = document.getElementById(span)

    // spanModal = document.getElementById(spanModal);   

    modalName.style.display='block';

    spanModal.onclick = function()
        {
            modalName.style.display = "none";
        }

});

最佳答案

改变

span = (modalName + "Span");

span = (modalName.id + "Span");

modalName 指的是 <div id="currentChildrenModal" class="modal">并获得currentChildrenModal您需要使用modalName.id并附加Span获取跨度 <span class="close" id="currentChildrenModalSpan">&times;</span> 的句柄

关于javascript - 由于未捕获类型错误 : Cannot set property 'onclick' of null,无法关闭 Modal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46626733/

相关文章:

javascript - 动画两个div以无限期地从右到左循环

javascript - 使用 Jquery 动态添加一个元素到我的表单

javascript - "gameActivity" key 在开始时更改但应该停止

JavaScript 连接

javascript - 为什么 React.Js 模板和 Angular 模型之间没有绑定(bind)?

javascript - jQuery 中的一个简单字典列表

javascript - Chrome 选项卡内存不断增长,堆大小保持不变

javascript - 为什么我不能让我的表单关闭,以便我可以访问导航栏?

c# - Url.PathAndQuery 出现错误

javascript - 在 react jsx 中显示 html 标记