简体   繁体   English

Google Chrome浏览器扩展程序看不到点击?

[英]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. 以下是我的Chrome扩展程序。 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 元素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. 当您执行document.querySelector('.overlay_show') ,它将选择具有类.overlay_show的第一个元素,并在其上添加一个侦听器。 Done . 完成

So, you have 2 solutions: 因此,您有2个解决方案:

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 监听单击<body>并使用e.target

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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