2011-10-25 42 views
0

我想将onclick事件添加到使用如下因素代码生成一个div:jQuery:如何将onlick事件添加到动态生成的div?

$("<div />").attr("city", $(this).attr("city")) 
      .attr("state", $(this).attr("state")) 
      .html($(this).attr("city") + ',' + $(this).attr("state")) 
      .appendTo($('#cityList')); 

我应该写在HTML点击数事件()?

+0

为什么不.bind(),它直接.appendto后()? – mddw

回答

2

为什么不分开div的创建和其余代码的链接。例如

var elem = $('<div />'); 
elem.click(function() { 
    // Click handler 
}); 

elem.attr("city", $(this).attr("city")) 
    .attr("state", $(this).attr("state")) 
    .html($(this).attr("city") + ',' + $(this).attr("state")) 
    .appendTo($('#cityList')); 
相关问题