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