[英]these my code i written for When the user clicks anywhere outside of the modal, close it but it is not working .what is the wrong in my code
这些是我为我编写的代码,当用户单击模态之外的任何位置时,请关闭它,但不起作用。我的代码出了什么问题。 “框搜索”,“登录”,“注册”元素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-您比较event.target与模式数组元素,而不是它的id
3-您尝试将样式分配给字符串(modal [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";
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.