jquery adding click event to dynamically created element

故事扮演 提交于 2019-12-12 15:37:37

问题


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......
       });
     });


来源:https://stackoverflow.com/questions/6199468/jquery-adding-click-event-to-dynamically-created-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!