Jquery adding click event to dynamically created element

I need to add a click event to a list item that I create dynamically after loading the DOM.

I use;

$("#ListDiv li").live("click",function(event){
  do something......
 });

however, when an element is loaded onto the page and I click on it, I get nothing.

This works fine in Firefox, but not in IE8. I also tried jquery livequery and deleagte but didn't work. I tried debugging IE8 developer tools, but the method was never reached

+3
source share
2 answers

Use .delegateor .liveand make sure you bind once the DOM is ready :

$(document).ready(function () {
    $("#ListDiv").delegate("li", "click", function (event) {
        // do something
    });
});

EDIT:

, , /. jQuery .on() method:

jQuery 1.7, .on() .

.delegate, , , :

$(document).ready(function () {
    $("#ListDiv").on("click", "li", function (event) {
        // do something
    });
});
+10

document.ready

 $(document).ready(function() {
       $("#ListDiv li").live("click",function(event){
        do something......
       });
     });
+2

All Articles