当我运行以下代码时,当我单击下拉菜单的“当前子项”选项时,相应的模态框会显示在我的屏幕上,但随后我无法将其关闭,因为我在“
”处收到以下错误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">×</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">×</span>
的句柄
关于javascript - 由于未捕获类型错误 : Cannot set property 'onclick' of null,无法关闭 Modal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46626733/