【问题标题】:Binding event before Creating DOM in jQuery在jQuery中创建DOM之前的绑定事件
【发布时间】: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, ... ,我想将事件绑定到子节点。

任何建议都会有所帮助,谢谢~

Fiddle Here

【问题讨论】:

  • 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


【解决方案1】:

你可以试试这个方法:

  • 定义一个&lt;div&gt;&lt;/div&gt;
  • 设置其idinnerHtml
  • 将其与onclick 事件绑定(提醒其id
  • 将其附加到“#parent”项

$(function() {
    for (var i = 0; i < 10; i++) {
        $("<div></div>")
            .attr("id", "div-" + i)
            .html("DIV-" + i)
            .click(function() {
                alert($(this).attr("id"));
            })
            .appendTo("#parent");
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多