I’m having trouble appending a get() to a dynamically created div. I’ve marked with a comment the code that’s giving me trouble. Can someone please take a look and see what’s wrong with it?
var weekday = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
today = new Date().getDay(),
list = $('ul.yui-nav');
for(var x=0;x<=6;x++){
$('#' + weekday[x]).hide();
list.append(
$('<li></li>', {
html : '<a href = "#' + weekday[x].toLowerCase() + '">' + weekday[x] + '</a>'
}).toggleClass(function(){
if(today == x){
return 'selected';
}
}).bind('click', function(e){
e.preventDefault();
$(this).parent().children('li').removeClass('selected');
$(this).addClass('selected');
$('#' + weekday[x]).hide();
$('#' + weekday[x]).show();
})
);
// the 5 lines below is where I'm having trouble
$('div.yui-content').append(
$('<div class="content" id="' + weekday[x] + '"></div>').append(
$.get('index.php')
)
);
}
$.getreturns a XHR object, not a string of HTML or a valid HTML element.$.getis also asynchronous so you need to use it’s callback to be able to use it’s response from the server:Since you are concocting a string of HTML anyway, you could just put the
serverResponsedirectly into the creation of the.contentdiv:Update
Since you are running this inside a loop you can use a closure to keep the value of
xintact for the callback function:This is necessary because when the callback function executes, the value of
xin the scope of the loop will have changed. Using a closure we are basically creating a new scope (function) in which the value ofxis “saved” (asnewX) until it is needed (which could be anytime in the future).Also, I would suggest buffering the HTML that you are appending to the DOM and adding it at once, rather than calling
.append()each iteration of the loop:Then after your loop is done running: