尝试创建带有可折叠标题的列表,但是当我在列表内部单击时,它会折叠。

这是我的JavaScript,(我还不知道jQuery)

function comFunc() {
document.getElementById("Community").classList.toggle("show");

document.onclick = function(event) {
    var x = document.getElementById("Community");
    var y = document.getElementById("comarrow");

        if (x.classList.contains("show")) {
            y.classList.remove("glyphicon-menu-right");
            y.classList.add("glyphicon-menu-down");
        } else {
            y.classList.remove("glyphicon-menu-down");
            y.classList.add("glyphicon-menu-right");
            }
        }
window.onclick = function(event) {
        var x = document.getElementById("Community");
        var y = document.getElementById("comarrow");

        if (!event.target.matches('.resbtn')) {
            x.classList.remove('show');
            y.classList.remove("glyphicon-menu-down");
            y.classList.add("glyphicon-menu-right");
            }
        }
}


我尝试使用“ ||”如

if (!event.target.matches('.resbtn' || '.dropdown-content')) {


但这似乎不起作用。

有什么想法吗?

最佳答案

Selectors中所述,您需要使用逗号将两个选择器组合在一起。

因此,更改为:

if (!event.target.matches('.resbtn' || '.dropdown-content')) {


至:

if (!event.target.matches('.resbtn, .dropdown-content')) {




document.querySelectorAll('button').forEach(function(ele, idx) {
   ele.addEventListener('click', function(e) {
       var x = event.target.matches('.resbtn, .dropdown-content');
       console.log('matches=' + x + '\nhtml:' + this.outerHTML);
   });
});

<button id="btn1" class="resbtn">Click Me</button>
<button id="btn2" class="dropdown-content">Click Me</button>
<button id="btn3" class="noOne">Click Me</button>

10-07 19:08
查看更多