Javascript 这些是我为之编写的代码,当用户单击模式之外的任何位置时,关闭它,但它不工作。我的代码中有什么错误
这些是我为之编写的代码,当用户单击模式之外的任何位置时,关闭它,但它不工作。我的代码中有什么错误。 “框搜索”、“登录”、“注册”元素id名称Javascript 这些是我为之编写的代码,当用户单击模式之外的任何位置时,关闭它,但它不工作。我的代码中有什么错误,javascript,Javascript,这些是我为之编写的代码,当用户单击模式之外的任何位置时,关闭它,但它不工作。我的代码中有什么错误。 “框搜索”、“登录”、“注册”元素id名称 <script> var modal = ["box-search","login","register"]; for(var i=0;i<3;i++) { window.onclick = function(event) { if (event.target == modal[i]) {
<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>
var modal=[“框搜索”、“登录”、“注册”];
对于(var i=0;i您的window.onClick错误:
1-你在函数外循环你的模态,你应该在函数内循环,让它正常工作
2-将event.target与模态数组元素进行比较,而不是将其id进行比较
3-尝试将样式指定给字符串(模态[i]),而不是event.target对象
这是重写的函数(应该可以工作)
window.onclick=函数(事件){
对于(var i=0;i每次迭代循环时,都会清除窗口的最后一个值。单击并将新函数设置为其值。使用.addEventListener()
注册事件处理程序
话虽如此,您在回调函数中使用i
时遇到了一个问题,因为i
是在更高的级别上声明的,因此在它周围创建了一个闭包。您可以阅读有关闭包的更多信息。闭包导致事件处理函数都在寻找模式[3]
因为这是循环退出时设置的最后一个值i
为避免关闭并更正对窗口的覆盖。单击,脚本应为:
<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.addEventListener(“单击”,testModal)
函数testModal(事件){
var modal=[“框搜索”、“登录”、“注册”];
//使用内置的Array.prototype.forEach方法进行循环
//通过数组元素,从而避免使用数字计数器
modal.forEach(函数(元素){
//在DOM中搜索id为的元素
//匹配模态数组的id
var el=document.getElementById(元素);
//检查找到的元素
如果(event.target==el){
el.style.display=“无”;
}
});
}
每次迭代循环时,都可能会删除窗口的最后一个值。单击并将新函数设置为其值。使用.addEventListener()
注册事件处理程序。@Baswaraj不客气。别忘了对帮助您的答案进行投票。
<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>