[removed] how to re-attach the same event listener to a element reppeared?

前端 未结 2 389
时光取名叫无心
时光取名叫无心 2021-01-27 08:04

In my code, I have a h1 container with h1 element inside like below :

Title H1

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-27 09:07

    Instead of h1.addEventListener(...) add

    document.body.addEventListener('click', function(element) {
        if (element.target.nodeName == 'H1') {
            // your code
        }
    })
    

    So you bind event listener to body rather than h1. The thing is that your h1.addEventListener(...) is only applied on currently in DOM existing

    elements, but not on dynamically created ones.

    http://www.theappguruz.com/blog/dynamic-event-binding-demo-jquery

    In jQuery, how to attach events to dynamic html elements?

提交回复
热议问题