javascript 这个.includes()方法有什么问题?

yftpprvb  于 2023-09-29  发布在  Java
关注(0)|答案(1)|浏览(78)
const ul1 = document.querySelector("#ul1");
const ul2 = document.querySelector("#ul2");
const tableRow1 = document.querySelectorAll("#ul1 .td");
const tableRow2 = document.querySelectorAll("#ul2 .td");

ul1.addEventListener('click', function (e) {
    if (e.target.classList.contains("td")) {
        e.target.classList.toggle("selected");
        if (![...tableRow1].includes(document.querySelector(".selected"))) {
            console.log('true1');
        }
    }
})

ul2.addEventListener('click', function (e) {
    if (e.target.classList.contains("td")) {
        e.target.classList.toggle("selected");
        if (![...tableRow2].includes(document.querySelector(".selected"))) {
            console.log('true2');
        }
    }
})
.selected{
  background: rgba(0, 182, 94, 0.08);
}
<ul id="ul1">
    <li class="td">dsfds</li>
    <li class="td">sdfdsf</li>
    <li class="td">sdfsfs</li>
    <li class="td">sfdsfds</li>
    <li class="td">sfdssfs</li>
</ul>

<ul id="ul2">
    <li class="td">sfdss</li>
    <li class="td">sfsdfdsf</li>
    <li class="td">sfssfsf</li>
    <li class="td">sfsdsds</li>
    <li class="td">sdfsfds</li>
</ul>

如果从第一个列表中选择了一个,那么第二个list.include()方法就不工作了,为什么会这样?无论第一个列表中选择了多少个,如果第二个列表中的所有未选中,那么它应该返回true。

p4rjhz4m

p4rjhz4m1#

ul1.addEventListener('click', function (e) {
    if (e.target.classList.contains("td")) {
        e.target.classList.toggle("selected");
        if (![...tableRow1].includes(ul1.querySelector(".selected"), 0)) {
            console.log('true1');
        }
    }
})

ul2.addEventListener('click', function (e) {
    if (e.target.classList.contains("td")) {
        e.target.classList.toggle("selected");
        if (![...tableRow2].includes(ul2.querySelector(".selected"), 0)) {
            console.log('true2');
        }
    }
})

相关问题