Justin White
Justin White

Reputation: 714

jQuery append() - looks to me like it should work but doesn't

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')
            )
        );

    }

Upvotes: 1

Views: 140

Answers (2)

Jasper
Jasper

Reputation: 75993

$.get returns a XHR object, not a string of HTML or a valid HTML element.

$.get is also asynchronous so you need to use it's callback to be able to use it's response from the server:

    //make AJAX call to `index.php`, storing the server-response in the `serverResponse` variable
    $.get('index.php', function (serverResponse) {

        //select the element to append-to
        $('div.yui-content').append(

            //create a new div and append the server-response to it
            $('<div class="content" id="' + weekday[x] + '"></div>').append(serverResponse));
    });

Since you are concocting a string of HTML anyway, you could just put the serverResponse directly into the creation of the .content div:

        $('div.yui-content').append(
            $('<div class="content" id="' + weekday[x] + '">' + serverResponse + '</div>'));

Update

Since you are running this inside a loop you can use a closure to keep the value of x intact for the callback function:

(function(newX) {
    $.get('index.php', function (serverResponse) {
        $('div.yui-content').append(
            $('<div class="content" id="' + weekday[newX] + '"></div>').append(serverResponse));
    });
})(x);

This is necessary because when the callback function executes, the value of x in the scope of the loop will have changed. Using a closure we are basically creating a new scope (function) in which the value of x is "saved" (as newX) 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:

 list = [];

    for(var x=0;x<=6;x++){
        $('#' + weekday[x]).hide();
        list.push(...

Then after your loop is done running:

for (...) {...}
$('ul.yui-nav').append(list.join(''));

Upvotes: 4

ShankarSangoli
ShankarSangoli

Reputation: 69905

$.get does an ajax call which in async by nature and it returns an xhr object. So either execute your code inside $.get's callback or you can use load method like this.

$('<div />', { 
      class: "content", 
      id: weekday[x] 
})
.appendTo('div.yui-content')
.load('index.php');

Note, I am using appendTo method to append the dynamically created div.content inside div.yui-content.

If you use load then you don't have to create closure because the div is already created before calling load.

Upvotes: 0

Related Questions