0

I use ajax to create dynamic div, and want to get notified when I click the "a" inside div which id='listall', but it's not working, why? How to correct it. thanks here is the code:

$(function(){


$.ajax({
            type: "GET",
            url: 'http://XXX:8080/',
            dataType:'json',
            contentType:"application/json",
            success:function(data){
                console.log(data);
                var projectList="<ul style='list-style:none;'>"

                for (var i = 0; i < data.data.length; i++) {

                        projectList += "<li><div id='listall'><a href='/projectDetail'>"+ 
                          "<img class='back' src='data.data[i]'></li>"
                }
             var projectList +="</ul>"

            },
            error:function(){
                    alert("connection error");
            }
}); 



    $('#listall').on('click', 'a', function (){
            console.log('click!');
            alert("finally");
    });
});
Casey Cao
  • 341
  • 3
  • 15
  • Instead of `$('#listall')` use static element – Satpal Jun 20 '17 at 08:06
  • I got the id of a through click function, and I want to alert the value of id, by doing like this, I get null, how should I correct it? var projectId=null; $('body').on('click', '#listall a', function (){ projectId=this.id; //id=30 }); alert(projectId); thank you – Casey Cao Jun 20 '17 at 08:35

2 Answers2

3

Delegate the event

$('body').on('click', '#listall a', function (){
            console.log('click!');
            alert("finally");
    });
brk
  • 48,835
  • 10
  • 56
  • 78
  • thanks, i want to get id of clicked a and alert it outside the function, how could i do it? $('body').on('click', '#listall a', function (){ var projectId=this.id; }); alert(projectId); this doesn't work show undefined – Casey Cao Jun 20 '17 at 08:26
2

you should use

$(document).on('click','#listall a',function(){
     console.log('click!');
        alert("finally");
});
Dij
  • 9,761
  • 4
  • 18
  • 35