2011-11-01 60 views
3

我的当前设置加载在这一点我通过jQuery创建点击事件,像这样的动态列表:如何将jquery Click事件应用于动态列表元素?

$('#listReports li').click(function() { 
    var selected = $(this).text(); 
    alert("List Item: " + selected); 
}); 

我有代码,允许用户保存其被附加到列表的报告。在我再次调用函数之前,列表中的新项目不会触发单击事件。问题在于旧的项目事件被触发两次。

这是我如何追加我的列表项,并调用然后再次发挥作用:

  $("#save").click(function (e) { 

       if ($("#reportParams li").size()> 0) { 
        var fileName = $('#reportFileName').val(); 

        if (!fileName) { 
         alert("You must enter a file name!"); 
        } 
        else { 
         $('#listReports').append('<li><a href="#">'+fileName+'</a></li>'); 

         $('#listReports li').click(function() { 
          var selected = $(this).text(); 
          alert("List Item: " + selected); 
         }); 
        } 
       } 
      }); 

有没有办法只能定义一次点击事件并将其影响追加到列表中的新项目?

回答

4

相反的.click(),使用.live()

$('#listReports li').live('click', function() 
{ 
    var selected = $(this).text(); 
    alert("List Item: " + selected); 
}); 

.delegate()

$('#listReports').delegate('li', 'click', function() 
{ 
    var selected = $(this).text(); 
    alert("List Item: " + selected); 
}); 
+0

的作品太好了!现场和委托有什么区别?一个比另一个更好吗? – Paul

+0

http://stackoverflow.com/search?q=jquery+live+vs+delegate –

+0

[.live()](http://api.jquery.com/live/)在jQuery 1.7+中已弃用。改为使用[.on()](http://api.jquery.com/on/) – rawbeans

相关问题