How to addEventListener to future dom elements?

前端 未结 1 366
执念已碎
执念已碎 2021-01-02 08:38

File partial.html looks like this:

Partial.html is dynamically included on

1条回答
  •  感动是毒
    2021-01-02 09:00

    Events like click bubble, so you attach the event handler to the closest non-dynamic parent, and inside the event handler you check if it was the button being clicked by seeing if it was the event's target :

    var parent = document.getElementById('pageArea');
    
    if (parent.addEventListener) {
        parent.addEventListener('click', handler, false);
    }else if (parent.attachEvent) {
        parent.attachEvent('onclick', handler);
    }
    
    function handler(e) {
        if (e.target.id == 'test') {
             // the button was clicked
        }
    }
    

    FIDDLE

    0 讨论(0)
提交回复
热议问题