当用户单击模式外的任何地方时,我为其编写的代码,关闭它,但它无法正常工作。我的代码中有什么错误。"盒子搜索","登录","寄存器"元素ID名称。
<script>
var modal = ["box-search","login","register"];
for(var i=0;i<3;i++) {
window.onclick = function(event) {
if (event.target == modal[i]) {
modal[i].style.display = "none";
}
}
}
</script>
每次迭代循环时,您都在删除window.onclick
的最后一个值并将新函数设置为其值。使用.addEventListener()
注册事件处理程序。
现在,话虽如此,您在回调功能中使用i
有问题,因为i
在较高级别上声明,因此围绕它创建了封闭。您可以在此处阅读有关关闭的更多信息。封闭使事件处理函数都引起所有查找modal[3]
,因为这是循环退出时的最后一个值i
。
要避免关闭并纠正window.onclick
的覆盖,脚本应为:
<script>
// Use modern standards to set up event handlers:
window.addEventListener("click", testModal)
function testModal(event){
var modal = ["box-search","login","register"];
// Use the built-in Array.prototype.forEach method to loop
// through the array elements, thus avoiding a numeric counter
modal.forEach(function(element){
// Search the DOM for elements that have id'sthat
// match the modal array's id's
var el = document.getElementById(element);
// Check the found element
if (event.target == el) {
el.style.display = "none";
}
});
}
</script>
您的window.onclick是错误的:
1-您在功能之外的模态上循环,您应该在内部做才能使其正常工作
2-您将事件与模态数组元素进行比较,而不是ID
3-您尝试将样式分配给字符串(模态[i])而不是为您的event.target对象
这是重写的功能(应该工作)
window.onclick = function(event) {
for(var i=0;i<3;i++) {
if (event.target.id == modal[i]) {
event.target.style.display="none";
}
}
}