jquery将click事件添加到动态创建的元素中 [英] jquery adding click event to dynamically created element

查看:147
本文介绍了jquery将click事件添加到动态创建的元素中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我加载DOM后动态创建的列表项中添加一个click事件。

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

我正在使用;

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

但是当元素加载到页面上并且我点击它时我什么也得不到。

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

这适用于Firefox,但不适用于IE8。我也试过jquery livequery和deleagte,但都没有用。我尝试使用IE8开发人员工具进行调试,但是方法永远不会到达

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

推荐答案

使用 .delegate .live 并确保在 DOM准备就绪后绑定:

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

编辑:

以上解决方案,虽然仍然完全有效,但现在是遗留/弃用。 jQuery之后推出了 .on()方法

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


从jQuery 1.7开始,.on()方法提供了附加事件处理程序所需的所有功能

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

该实现与上面发布的 .delegate 解决方案非常相似,但要注意参数的顺序已更改:

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

这篇关于jquery将click事件添加到动态创建的元素中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆