2012-03-21 39 views
1

我有一个没有列表项的无序列表。将事件绑定到AJAX填充列表项

我从用户那里得到了一些信息,我使用AJAX通过数据库运行它,服务器发回一个JSON对象响应。

然后我附上我想用的东西展示给列表像

$('blabla').append('<li>information</li>') 

我的问题是每个列表项,因为li元素都没有了当时的DOM准备好了,我该怎么绑定点击事件给他们?

这里是我的全码:

$(function(){ 
var timer; 
$('#f').keyup(function(){ 
    clearTimeout(timer); 
    timer = setTimeout(getSuggestions, 400); 
    }); 
}) 

function getSuggestions(){ 
var a = $('#f')[0].value.length; 
if(a < 3){ 
    if(a == 0){ 
     $('#ajaxerror').hide(300,function(){ 
      $('#loading').hide(300,function(){ 
       $('#suggest').hide(300) 
       }) 
      }) 
     } 
    return; 
    } 
$('#loading').slideDown(200,function(){ 
    $.ajax({ 
     url: '/models/AJAX/suggest.php', 
     dataType: 'json', 
     data: {'data' : $('#f')[0].value }, 
     success: function(response){ 
      $('#ajaxerror').hide(0,function(){ 
       $('#loading').hide(100,function(){ 
        $('#suggest ul li').remove(); 
        for(var b = 0; b < (response.rows * 3); b = b + 3){ 
         $('#suggest ul').append('<li>'+response[b]+' '+response[b+1]+' '+response[b+2]+'</li>') 
         // MISSING SOME CODE HERE TO BIND CLICK EVENT TO NEWLY CREATED LI 
         } 
        $('#suggest').show(300) 
        }) 
       }) 
      }, 
     error: function(){ 
      $('#suggest').hide(0,function(){ 
       $('#loading').slideUp(100,function(){ 
        $('#ajaxerror').show(300) 
        }) 
       }) 
      } 
     }) 
    }) 
} 

回答

2

您使用on()

http://api.jquery.com/on/

for(var b = 0; b < (response.rows * 3); b = b + 3){ 
     (function(b) { 
     $('#suggest ul').append('<li>'+response[b]+' '+response[b+1]+' '+response[b+2]+'</li>'); 
     $('#suggest ul li').on('click', function() { 
      // your function` 
     }); 
     })(b); // this is needed so that your click event has a proper access to variable b just before it changes to b+3 
    } 
+0

谢谢您的时间。你能举个例子吗? – ppp 2012-03-21 03:07:38

+0

编辑,看看是否有帮助:) – 2012-03-21 03:12:31

+0

它的确如此,谢谢。关于//你的函数部分的最后一件事。当在这个功能中,我尝试提醒响应[b],它提醒“未定义”。我怎么能通过这个?当有人点击新创建的li时,我试图改变其他元素。 – ppp 2012-03-21 03:22:27