【发布时间】:2016-05-27 13:49:14
【问题描述】:
var thumbDom = '';
for (var i = 0; i < 10; i++) {
thumbDom = thumbDom + '<div id = "div-" ' + i + '>DIV-'+ i +'</div>';
bindEvent(i);
}
$('#parent').append(thumbDom);
function bindEvent(i){
$('#div-' + i).click(function(event) {
alert(i);
});
}
我知道代码不能工作,因为事件是在 dom 追加之前绑定的。 但是在附加到 dom 树之前,有没有办法将 click 事件绑定到许多动态 dom?
我不想使用 $(document).on('click, ... ,我想将事件绑定到子节点。
任何建议都会有所帮助,谢谢~
【问题讨论】:
-
I don't wnat to use $(document).on('click, ... , I want to bind event to the child node.为什么?事件委托正是在这里使用的模式。 -
在
.append之后调用bindEvent但@RoryMcCrossan 是正确的,因为我找不到任何理由来避免这种模式......
标签: javascript jquery events append