Get children after append jquery mobile?
I have an empty list at the start like this.
<ul id="list" data-role="listview" data-inset="true">
</ul>
Within the document ready function, I call multiple
$('#list').append开发者_高级运维('<li id="a">A</li>').listview('refresh');
to the ul each having its own unique id. So the result should be like:
<ul id="list" data-role="listview" data-inset="true">
<li id="a">A</li>
<li id="b">B</li>
</ul>
But at the end of the body tag in HTML, when I try doing something like
$('#list').children()
It comes up as empty set [].
Likewise when I attach a click event with something like $("#a").click(function{alert("A")})
it doesnt work at all as it doesnt recognize the #a since it was dynamically created maybe?
I hope someone can help me with whats going on and if there is a way around this.
you need to use jquery live function to bind events to dyanamicaly added data.Try this.
$("#a").live('click',function(){
alert("A");
});
Don't know about the .children thing. Sounds weird.
The click event is because the items were created dynamically yeah.
So to get around this, add a class to each of the items.
<li id="a" class="ListItem">A</li>
Then you can use the each keyword to itterate through the list.
As for a click event use the live keyword.
$(".ListItem").live("click", function() { your code here })
When using jQuery mobile, you can't use the document ready handler like you normally would. Since pages are brought in with ajax, the document ready handler is only fired once (whatever page the user lands on first). You should bind to the pagecreate
(events) event instead.
Also, like others have mentioned, you'll need to use live
to handle your click events for dynamically added content.
You could do this:
<script type="text/javascript" src="jquery-1.6.3.min.js"></script>
<script>
$(document).ready(function(){
$('#list').append('<li id="a">A</li>')
.append('<li id="b">B</li>')
.append('<li id="c">C</li>');
});
</script>
<ul id="list" data-role="listview" data-inset="true"></ul>
<script>
setTimeout(function(){
$('#list').children("li").each(function(){
alert($(this).attr("id"));
});
},100);
</script>
The setTimeout it what makes it work
精彩评论