-3

Even though this is a duplicate question of "Event handler not working on dynamic content" , I am stuck with the same problem even after following the answers given there. Please help ....

    userinfo.topics.forEach(ele=>{
            $("#topics_subscribed").append(`<li class="list-group-item col-4">${ele} &nbsp;<i style="color:red;font-size:.7em;" class="removeitem fa fa-times"/></li>`) ;
        });


    $(document).on('click', '.removeitem', ()=> {
        console.log('clicked') ; 
        $(this).parent().remove() ; 
    });

Please answer why its happening before marking this as duplicate . How to fix this ? (I will remove the question as soon as its answered please....)

Natesh bhat
  • 12,274
  • 10
  • 84
  • 125
  • 2
    Your problem is that you're _not_ following the answer on the other question, because you're using an arrow function `()=>` which behaves differently with regards to the scope of `this`. If you switch it out for a regular anonymous function as per the answer you reference, it should work. – delinear Jan 05 '18 at 14:05
  • It might be good to comment on the original question to include your question and answer, so other people can read further and find the solution if they run into the same frustration. – adprocas Jan 05 '18 at 14:08

1 Answers1

5

It is because you are using an arrow function which has no explicit this

Change to:

$(document).on('click', '.removeitem', function(){
    console.log('clicked') ; 
    $(this).parent().remove() ; 
});
charlietfl
  • 170,828
  • 13
  • 121
  • 150