简体   繁体   中英

Google Chrome Extension Can't See Clicks?

I can't get any of these event listeners to trigger any functions.

The below is in my chrome extension. The alert is triggered but none of the listeners work. The elements are created dynamically so I'm not sure if that makes a difference.

document.addEventListener('DOMContentLoaded', function() {
    document.querySelector('.overlay_show').addEventListener('click', alertit);
    document.querySelector('.overlay_hide').addEventListener('click', alertit);
});

element html

`<a class='overlay_hide' ><i>Hide<i/></a>`;

`

Any ideas would be helpful?

The elements are created dynamically so I'm not sure if that makes a difference.

It does. If you add the listener before you add the elements, it won't work. When you do document.querySelector('.overlay_show') , it selects the first element that has the class .overlay_show , and adds a listener upon it. Done .

So, you have 2 solutions:

Add the listener after you add the element

But it means that you have to do that each time you do so

Listen for a click on <body> and use e.target

document.body.addEventListener('click', function (e) {
    if (e.target.classList.contains('overlay_show')
        || e.target.classList.contains('overlay_hide')) {
        alertit()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM