Attach event to dynamic elements in javascript

前端 未结 10 2279
一生所求
一生所求 2020-11-21 23:16

I\'m trying to insert html data dynamically to a list that is dynamically created, but when i try to attach an onclick event for the button that is dynamically created the e

10条回答
  •  旧时难觅i
    2020-11-21 23:44

    This is due to the fact that your element is dynamically created. You should use event delegation to handle the event.

     document.addEventListener('click',function(e){
        if(e.target && e.target.id== 'brnPrepend'){
              //do something
         }
     });
    

    jquery makes it easier:

     $(document).on('click','#btnPrepend',function(){//do something})
    

    Here is an article about event delegation event delegation article

提交回复
热议问题