0
<ul>
<li>
<a href='javascript:;' class='close'>close</a>
<a>openId</a>
</li>
</ul>

I want to remove the li element when click a.close.The li is generate dynamic, which means each time a new li was generated, I will do something like this.

$("a.close").unbind("click").click(function(){
    console.log("close click");
})

however, it didn't work as expected, when I type $("a.close").click() in chrome console, it print "close click" as expected, but when I click the a.close area with mouse, it didn't show anything, which means the event didn't trigger.

what is the difference between js's click function and mouce click using hands?

teik
  • 474
  • 4
  • 19

1 Answers1

0

when you bind any event to any HTML element it will work fine... but once you remove that element from DOM and again add same element into DOM you need to bind click event again for that newly added element. So it is become difficult ... instead of this .. you can just register click event (as below) then no need to bind event again and again ... Any newly added HTML element will also get the same event ....

Note:- note that the elements that should match (a.close in this case) need not exist at the time of binding (hence it applies to dynamically added elements as well).

You just need to register your click event as below ...

$('body').on("a.close","click",function(){
      alert('click event fired !')
});
prog1011
  • 3,157
  • 3
  • 20
  • 49