jquery adding click event to dynamically created e

2019-07-04 03:02发布

问题:

i have the need to add a click event to a list item i create dynamically after the DOM has loaded.

I'm using ;

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

however when the element is loaded on the page and i click it i get nothing.

This works fine in Firefox but not in IE8. I also tried jquery livequery and deleagte but neither worked. I tried debugging with IE8 developer tools but the method is never reached

回答1:

Use .delegate or .live and make sure you bind once the DOM is ready:

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

EDIT:

The above solution, while still perfectly valid, is now legacy/deprecated. jQuery has since introduced the .on() method:

As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers.

The implementation is quite similar to the .delegate solution posted above, but be aware that the order of parameters has changed:

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


回答2:

push your code inside document.ready

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