2

I want to select the elements created dynamically using ajax by id, the code is:

$(function(){
   $('#loadFeed').bind('click',function(){ 
        $.getJSON('getData.php', function(json) {
            var output="<ul id='feedsList'>";

            for(var i=json.posts.length-1;i>=json.posts.length-31;i--){
                output+="<li class='post'>";
                output+="<div class='text' id='"+json.posts[i].id+"'>"+json.posts[i].shortmsg+"</div>";         
                output+="</li>";
            }
            output+="</ul>"
            $(output).appendTo('.posts');
    });
  });
});

The html codes:

<div class="posts">
    <!--dynamic content here-->
</div>

I tried to get the id using $(this).attr("id"):

$(".post").on("click",".text",function(){
      var this_id =$(this).attr("id");
      alert(this_id);
});

But it said undefined. How could I get the id correctly?Thanks!

Yujun Wu
  • 2,992
  • 11
  • 40
  • 56

2 Answers2

2

$(".post") should be $('div.post'), because you're creating li from ajax request with same class. As div.post is existing in your DOM and you're appending you list to it.

That is,

$("div.post").on("click","li.post div.text",function(){
      var this_id = this.id;
      alert(this_id);
});
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
  • 1
    You could make use of the DOM, and use `var this_id = this.id;` which is (marginally) faster, and avoids wrapping `this` needlessly in a jQuery object. – David Thomas May 18 '12 at 08:54
  • Actually when I changed to $(".posts").on("click",".text",function(){ var this_id =$(this).attr("id"); alert(this_id); }); It works! Anyway thx! – Yujun Wu May 18 '12 at 09:07
  • You're absolutely welcome, incidentally, in HTML 5 an `id` is allowed to start with a numeric character. Though there's no indication that the OP is using HTML 5. So it's a worthwhile warning regardless. – David Thomas May 18 '12 at 10:21
2

Numbers are not valid ids. Ids need to start with letters.

You will need to use something like this:

output+="<div class='text' id='post_"+json.posts[i].id+"'>"+json.posts[i].shortmsg+"</div>";

Here'se the structure of a valid id: What are valid values for the id attribute in HTML?

Community
  • 1
  • 1
Mihai Stancu
  • 15,848
  • 2
  • 33
  • 51