簡體   English   中英

為什么我的 JavaScript 事件偵聽器條件不起作用?

[英]Why does my JavaScript event listener condition not work?

此事件偵聽器,當我在文檔中的任意位置單擊執行,我想它,當我點擊不執行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';
            }
        });
}

感謝您的任何建議!

這已經解決了這個問題:

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

我一直在定位錯誤的元素,我試圖獲取的元素是父元素。

捕獲這些元素上的點擊事件並停止事件傳播:

this.dropdown.addEventListener('click', (e) => {
  console.log('Element clicked');
  e.stopPropagation();
});

https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM