简体   繁体   English

jquery 将点击事件添加到动态创建的元素

[英]jquery adding click event to dynamically created element

i have the need to add a click event to a list item i create dynamically after the DOM has loaded.我需要在 DOM 加载后动态创建的列表项中添加点击事件。

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.这在 Firefox 中可以正常工作,但在 IE8 中不行。 I also tried jquery livequery and deleagte but neither worked.我还尝试了 jquery livequery 和 deleagte,但都没有奏效。 I tried debugging with IE8 developer tools but the method is never reached我尝试使用 IE8 开发人员工具进行调试,但从未达到该方法

Use .delegate or .live and make sure you bind once the DOM is ready :使用.delegate.live并确保在DOM 准备好后进行绑定:

$(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 : jQuery 此后引入了.on() method

As of jQuery 1.7, the.on() method provides all functionality required for attaching event handlers.从 jQuery 1.7 开始,.on() 方法提供了附加事件处理程序所需的所有功能。

The implementation is quite similar to the .delegate solution posted above, but be aware that the order of parameters has changed:该实现与上面发布的.delegate解决方案非常相似,但请注意参数的顺序已更改:

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

push your code inside document.ready将您的代码推入 document.ready

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM