为什么我的 class 没有被这个 JavaScript 函数切换?

Why is my class not being toggled by this JavaScript function?

我正在尝试在单击 #datePickerStart div 时切换 .active class。它仅在我单击 div 时切换,但我希望在日期选择器外部单击时隐藏该元素。

$('#datePickerStart').addEventListener('click', (e) => {
    console.log(e.path);
    if (!checkEventPathForClass(e.path, 'booking-dropdown')) {
        $('#dropDownStart').classList.toggle('active');
    }
});

function checkEventPathForClass(path, selector) {
    for (item of path) {
        if (item.classList && item.classList.contains(selector)) {
            return true;
        }
    }
    return false;
}
.active {
    display: block;
}

JSBin for my website.

shouldToggleClass 创建一个单独的函数,并从两个事件侦听器调用该函数。您也可以直接使用 click 而不是 addEventlistener 因为 jquery 已经被使用

const $ = (selector) => {
  return document.querySelector(selector);
};

$('#datePickerStart').addEventListener('click',(e) => {
  shouldToggleClass(e)

});

function shouldToggleClass(e) {
  const isEventPath = checkEventPathForClass(e.path, 'booking-dropdown');
  if (!isEventPath) {
    $('#dropDownStart').classList.toggle('active');
  }
}


function checkEventPathForClass(path, selector) {
  for (item of path) {
    if (item.classList && item.classList.contains(selector)) {
      return true;
    }
  }
  return false;
}

$('body').addEventListener('click',(e) => {
  shouldToggleClass(e)
});

不是很好的 synthax :

`if (!checkEventPathForClass(e.path, 'booking-dropdown')) {
    $('#dropDownStart').classList.add('active');
}`

?

您需要在整个文档上声明 onclick 函数,然后您可以检查点击的 Dom 是否是日期选择器,或者只要点击发生就从日期选择器中删除活动 class。

document.addEventListener("click", function(e){
    if( e.target.id == "dropDonStart" ){
        $('#dropDownStart').classList.toggle('active');
    }else{
        $('#dropDownStart').classList.remove('active');
    }
});

未测试但应该可以。