繁体   English   中英

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

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

当我想通过 JS 监听动态创建的元素上的事件时,我需要借助监听 body 上的事件来更新 JS 正在监听的元素列表。 有没有一种简单优雅的方式来更新元素数据库,让 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. 所有demo-classes类都是使用createElement生成的,并且类是使用render function 中的setAttribute设置的。

当您想要更新getElementsByClassName function 中的项目数据库时,使用location.reload()刷新页面。 将变量和动态元素存储在 Session 存储/本地存储中,以便它在浏览器刷新后仍然存在。

暂无
暂无

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

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