if 语句正在运行,即使 event.target 不是指定的元素



我的网页上有一个简单的script,每当用户单击页面上的特定按钮时,它就会打开一个模式。

但是,由于某种原因,即使事件目标不是指定的元素,它仍然会触发模式打开。显然,这不应该发生,我对为什么会这样感到困惑。

下面是 JavaScript

document.onclick = function(e){
    var modalTrigger = document.querySelectorAll(".ts-modal__trigger"),
        modals = document.querySelectorAll(".ts-modal"),
        i;
    for(i = 0; i < modalTrigger.length; i++){ 
        if(e.target == modalTrigger[i] || modalTrigger[i].children){
            modal = document.getElementById(modalTrigger[i].getAttribute("data-activemodal"));
            // these two will trigger not matter if the if statement is true
            document.body.style.overflow = "hidden"; 
            modal.style.display = "block";
        }
    }
}

这是 HTML

<!-- trigger !-->
<a class="ts-modal__trigger" data-activemodal="ts-main-feed_status-comments-overlay">
    <span data-rot="11">11</span>
</a>
<!-- modal !-->
<div class="ts-modal" id="ts-main-feed_status-comments-overlay"></div>

感谢所有帮助,

谢谢。

这行代码有两个问题:

if(e.target == modalTrigger[i] || modalTrigger[i].children)

首先,||无法测试e.target是否是多个可能值之一。条件的评估方式如下:

(e.target == modalTrigger[i]) || modalTrigger[i].children

第二个问题是modalTrigger[i].children是一个列表。它本身将永远是一个真实的价值。

所以你的 if 条件总是真的。

如果您想测试e.targetmodalTrigger[i]还是modalTrigger[i]的后代,我会这样做,方法是使用 .parentNode 属性从e.target向上导航以查看modalTrigger[i]是否是祖先:

function containsChild(parent, child) {
  while (child != null) {
    if (parent === child) return true;
    child = child.parentNode;
  }
  return false;
}
document.onclick = function(e){
    var modalTrigger = document.querySelectorAll(".ts-modal__trigger"),
        modals = document.querySelectorAll(".ts-modal"),
        i;
    for(i = 0; i < modalTrigger.length; i++){ 
        if(e.target == modalTrigger[i] || containsChild(modalTrigger[i], e.target)) {
            modal = document.getElementById(modalTrigger[i].getAttribute("data-activemodal"));
            // these two will trigger not matter if the if statement is true
            document.body.style.overflow = "hidden"; 
            modal.style.display = "block";
        }
    }
}
.ts-modal { display: none; }
<!-- trigger !-->
<a class="ts-modal__trigger" data-activemodal="ts-main-feed_status-comments-overlay">
    <span data-rot="11">This is a span in a trigger element</span>
</a><br>
<a>This is not a trigger</a>
<!-- modal !-->
<div class="ts-modal" id="ts-main-feed_status-comments-overlay">This is the overlay</div>

最新更新