简体   繁体   English

获取单击元素的类名

[英]Get class name of clicked element

I have some dynamically created divs . 我有一些动态创建的div。 And when the user clicks on the screen I want to check if it was on one of the dynamically created divs.But it doesnt seem to work. 当用户点击屏幕时,我想检查它是否在动态创建的div之一上。但它似乎不起作用。 I already have a window.addeventListener but that too is not working for the dynamically created divs. 我已经有了一个window.addeventListener,但它也不适用于动态创建的div。

            var divk = document.createElement("div");
            divk.className="divk";
             window.addEventListener('click', function(e){
                if (document.getElementById('outside_click_purpose').contains(e.target)){
                    currentItem = e.target;
                    if (currentItem.classList.contains("divk")) {
                      alert("contains !!!");
                    }
                }
           });

I think you need to use event delegation then use matches 我认为你需要使用event delegation然后使用matches

Notice how we use 注意我们如何使用

e.target.matches('.dynamic')

To check for the presence of our class, we can use any valid css selector 要检查我们类的存在,我们可以使用任何有效的css selector

For example, if we wanted to ensure it was a div: 例如,如果我们想确保它是div:

e.target.matches('div.dynamic');

See the demonstration below: 见下面的演示:

 // Add some dynamic divs const getDiv = (content) => { const div = document.createElement('div'); div.className = 'dynamic'; div.innerHTML = content; return div; }; const setMessage = (msg) => document.querySelector('.clicked').innerText = msg; document.addEventListener('DOMContentLoaded', () => { const container = document.querySelector('#container'); for(let i = 0; i< 10; i++) { container.appendChild(getDiv(`Dynamic ${i}`)); } }); // Use event delegation document.addEventListener('click', (e) => { if(e.target.matches('.dynamic')) { setMessage(`Clicked a dynamic div - text ${e.target.innerText}`); } else { setMessage('Click was not on dynamic'); } }); 
 .clicked { height: 20px; border: 1px solid red; } .manual { background-color: blue; color: white; } 
 <div class="clicked"></div> <div class="manual">Manual</div> <div class="manual">Manual</div> <div id="container"></div> 

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

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