由于未捕获的 TypeError: 无法设置 null 的属性“onclick”,因此无法关闭模式
2017-10-08
1129
当我运行以下代码时,当我单击下拉菜单的当前子项选项时,相应的模式会显示在我的屏幕上,但是我无法关闭它,因为我收到以下错误`
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";
}
});
3个回答
将
span = (modalName + "Span");
更改为
span = (modalName.id + "Span");
modalName 指的是
<div id="currentChildrenModal" class="modal">
,而要获取
currentChildrenModal
,您需要使用
modalName.id
并附加
Span
以获取 span 的句柄
<span class="close" id="currentChildrenModalSpan">×</span>
Phani Kumar M
2017-10-08
您的 modalName 应该是一个字符串,但以下行使其成为一个元素:
modalName = document.getElementById(modalName);
这就是为什么您的 span 变量不是获取元素的正确字符串。如果找不到,您无法将 onclick 附加到 spanModal 元素。一个好办法是尝试命名您的变量,以便您可以轻松地找出它们的含义。尝试以下操作:
$(".menu").on("click", function()
{
var modalFireButton;
var modalName;
var modalElm;
var spanModal;
var spanName;
modalFireButton = $(this).attr('id');
//set variable for corresponding modal
modalName = (modalFireButton + "Modal");
spanName = (modalName + "Span");
modalElm = document.getElementById(modalName);
spanModal = document.getElementById(spanName)
modalElm.style.display='block';
spanModal.onclick = function()
{
modalElm.style.display = "none";
}
});
Daniel H.J.
2017-10-08
您的代码的这一部分是错误的:
modalName = document.getElementById(modalName);
span = (modalName + "Span");
spanModal = document.getElementById(span)
因为您试图将 HTMLElement 与字符串连接起来。
Alex Santos
2017-10-08