首页 > 解决方案 > 为什么我的 JavaScript 事件侦听器条件不起作用?

问题描述

当我单击文档中的任意位置时执行此事件侦听器,我希望在单击this.dropdown或单击时不执行它this.inputField。现在,即使我单击这两个元素,它也会执行。

constructor(inputField, monthInput, previousMonth, nextMonth, dates, dropdown, document) {
        this.monthInput = monthInput;
        this.previousMonth = previousMonth;
        this.nextMonth = nextMonth;
        this.dates = dates;
        this.dropdown = dropdown;
        this.inputField = inputField;
        this.document = document;

this.document.addEventListener('click', (e) => {
            if (e.target.id !== this.dropdown.id && e.target.id !== this.inputField.id) {
                this.dropdown.style.display = 'none';
            }
        });
}

感谢您的任何建议!

标签: javascriptclassaddeventlistener

解决方案


这解决了这个问题:

checkPathForId(path) {
        for (let item of path) {
            if (item === this.dropdown || item === this.inputField) {
                return true;
            }
        }
        return false;
    }

我一直在定位错误的元素,我试图获取的元素是父元素。


推荐阅读