jquery loop with html?
I'm trying to loop results from a php script into my jquery friends list. Can't seem to get the list to show anything but undefined, but if I ap开发者_高级运维pend it to the body it only shows the last of the array. My code is...
$(function() {
$('<div />').html('<div id="buddies" class="buddies" style="vertical-align:bottom"><div class="imheader"> Online Favorites<span class="fr"><a href="#" id="exitlist">X</a></span></div><div class="imheader2"><div class="imheaderspan"><a href="#">Options</a></div></div><ul class="imwindow"><div id="myonlinefavs">' + FL() + '</div></ul></div><div id="chatbar" class="chatbar"><div id="ims"></div><div class="buddylist" id="buddylist"><center><a href="#" id="im-menu" class="im-menu">Favorites (<strong id="friendsonline">0</strong>)</a></center></div></div>').appendTo('body');
var imRoot = $("#im-menu");
var buddies = $("#buddies");
imRoot.click(function(){
buddies.toggle();
imRoot.blur();
return( false );
});
$("#exitlist").click(function(){
buddies.toggle();
imRoot.blur();
return( false );
});
$(document).click(function( event ){
if (buddies.is( ":visible" ) && !$( event.target ).closest( "#buddies" ).size()){
buddies.hide();
}
});
function FL(){
$.ajax({
type: 'POST',
url: 'config/receive_buddylist.php',
cache: 'false',
dataType: 'json',
success: function(data){
data && $.each(data, function(i, e){
if (i == "buddylist") {
$.each(e, function (l, f) {
if(f.id != null){
$('<div />').html('<li>' + f.n + '</li>');
}
});
}
});
}
});
}
});
The problem is you are doing $('body').html('<li>' + f.n + '</li>');
which continuously over-writes data. Try using append():
$('body').append('<li>' + f.n + '</li>');
I noticed you updated your code a bit. Here's a revamp:
if(f.id != null){
$('<div />').html('<li>' + f.n + '</li>').appendTo('body');
}
精彩评论