0

这是工作流程:

  1. 将元素动态添加到 div 容器
  2. 注册此元素的点击事件(使用 jquery 自定义函数)
  3. 触发元素事件

根据上面的流程,我无法让新元素事件起作用,因为它永远不会被触发。这是我的场景:

http://jsfiddle.net/9Ru76/1/

这个想法是,当您单击“元素”时,其 ID 属性应打印在 .log div 中

编辑:

我已经测试了所有答案,并且所有答案都可以正常工作:)

4

3 回答 3

3

You had the $(".element").showID(); outside the .create click handler so there was nothing to select, also you had your code in onLoad when it should be in no-wrap head.

http://jsfiddle.net/9Ru76/9/

于 2012-08-24T21:31:42.510 回答
1

You can use event delegation

$(document).ready(function(){

    $(".create").click(function(){
         $(".container").append('<div id="4" href="#" class="element">element</div>');
    });
});


    $(document).on('click','.element', function(){
        $(".log").html("id: " + $(this).attr("id"));
    });
于 2012-08-24T21:28:48.753 回答
0
于 2012-08-24T21:28:29.210 回答