[英]Get the id of elements dynamically created
I want to select the elements created dynamically using ajax by id, the code is: 我想通过ID选择使用Ajax动态创建的元素,代码为:
$(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: html代码:
<div class="posts">
<!--dynamic content here-->
</div>
I tried to get the id using $(this).attr("id"): 我试图使用$(this).attr(“ id”)获取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! 怎样才能正确获取ID?
$(".post")
should be $('div.post')
, because you're creating li
from ajax request with same class. $(".post")
应该是$('div.post')
,因为您是从具有相同类的ajax请求中创建li
。 As div.post
is existing in your DOM and you're appending you list to it. 由于div.post
在您的DOM中已经存在,因此您要向其添加列表。
That is, 那是,
$("div.post").on("click","li.post div.text",function(){
var this_id = this.id;
alert(this_id);
});
Numbers are not valid ids. 数字不是有效的ID。 Ids need to start with letters. ID必须以字母开头。
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? 有效ID的结构如下: HTML中id属性的有效值是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.