简体   繁体   English

需要一种简单的方法来更新动态元素数据库以便 JS 监听事件

[英]Need a simple way to update the dynamic element database for JS to listen to events

When I want to listen to events on dynamically created elements via JS, I need to resort to listening to the events on the body to update the element list JS is listening to.当我想通过 JS 监听动态创建的元素上的事件时,我需要借助监听 body 上的事件来更新 JS 正在监听的元素列表。 Is there not a simple elegant way to update the element database for JS to listen to when I want?有没有一种简单优雅的方式来更新元素数据库,让 JS 在我想听的时候听?

document.querySelector('body').addEventListener('click', function (event) {
    if (event.target.className.toLowerCase() === 'demo-classes') {
        let closeBtns = document.getElementsByClassName("demo-classes");
        Array.from(demoClasses).forEach(function (demoClass) {
            demoClass.addEventListener("click", function () {
                myArray.splice(demoClass.id.substring(2), 1);
                render(myArray);
            });
        });
    }
});

It leads to clicking two times, once on the body and another time on the element with the demo-classes class before the splice function removes the specific item from the arrays, then the render function renders the html. It leads to clicking two times, once on the body and another time on the element with the demo-classes class before the splice function removes the specific item from the arrays, then the render function renders the html. All demo-classes classes are generated using createElement and classes are set using the setAttribute in the render function.所有demo-classes类都是使用createElement生成的,并且类是使用render function 中的setAttribute设置的。

Use location.reload() to refresh your page when you want to update the database of items in getElementsByClassName function.当您想要更新getElementsByClassName function 中的项目数据库时,使用location.reload()刷新页面。 Store the variables and dynamically elements in Session Storage/Local Storage so that it survives browser refreshes.将变量和动态元素存储在 Session 存储/本地存储中,以便它在浏览器刷新后仍然存在。

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

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