简体   繁体   English

如何将数组添加到包含() javascript

[英]How to add array to includes() javascript

Im using composedPath for detect click outer of elements, but if elements more then 1 i need to add them all in if().我使用composedPath来检测元素的点击外部,但如果元素超过1我需要将它们全部添加到if()中。 Maybe in js have another way?也许在js中有另一种方式? Im trying.includes(document.querySelectorAll(".js-open-user"));我正在尝试.includes(document.querySelectorAll(".js-open-user")); But thats not work.但那是行不通的。

document.addEventListener("click", (event) => {
let b1 = event
        .composedPath()
        .includes(document.querySelectorAll(".js-open-user")[0]);

let b2 = event
        .composedPath()
        .includes(document.querySelectorAll(".js-open-user")[1]);

let b3 = event
        .composedPath()
        .includes(document.querySelectorAll(".js-open-user")[2]);

if (!b1 && !b2 && !b3) this.closeUser();
});

You can convert a NodeList to an array by using Array.prototype.slice.call() .您可以使用Array.prototype.slice.call()将 NodeList 转换为数组。 Then using Array.prototype.some() to check that at least one matches the criterion, if not you can use this.closeUser() which is not implemented in my example.然后使用Array.prototype.some()来检查是否至少有一个匹配标准,如果不匹配,您可以使用this.closeUser() ,这在我的示例中没有实现。

 document.addEventListener("click", (evt) => { const openUsers = Array.prototype.slice.call(document.querySelectorAll('.js-open-user')); const composedPath = evt.composedPath(); if (.openUsers.some(user => composedPath.includes(user))) { // no open users found..; alert('no matches;'); return; } alert('match!'); });
 <div class="js-open-user">hi</div> <div class="js-open-user">oop</div> <div class="js-open-user">test</div> <div class="js-open-user">last one</div>

const nodes = document.querySelectorAll(".js-open-user");
const intersection = event.composedPath().filter(n => nodes.includes(n));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM