views:

27

answers:

1

Hey there

I really don't know where the fault is all about. Here is my code:

$(document).ready(function(){
$("#folderTree > li").live('click',function(){
    var id = $(this).attr("id");
    if($('#' + id).hasClass('folderClosed')){
        $.ajax({
            url: "libs/php/ajax/documents/treeHandler.php",
            type: "POST",
            cache: false,
            dataType: "json",
            data: "treeNode=" + id,
            success: function(data){
                $('#' + id).removeClass('folderClosed');
                $('#' + id).addClass('folderOpen');
                $('#' + id).after('<ul id="#' + id + '-list">');
                $.each(data, function(){
                    var folder = '<li id=' + this.ID + ' class="folderClosed">' + this.folderName + '</li>';
                    $("#" + id + "-list").append(folder);
                })
                $('#' + id).after('</ul>');
            }
        })
    }else{
        $('#' + id).next("ul").remove();
        $('#' + id).removeClass('folderOpen');
        $('#' + id).addClass('folderClosed');
    }
})

})

I'm building a folder tree based on mysql data structur wich are loaded through ajax as json code. So far everything works fine!

My only problem is that my script isn't able to add the var folder to the new injected element.

Firebug example code:

<ul id="folderTree">
    <li class="folderOpen" id="1">100_Projektmanagement</li>
    <ul id="#1-list"></ul>
    <li class="folderClosed" id="3">200_Projektinitialisierung</li>
    <li class="folderClosed" id="4">300_Voranalyse_Studien</li>
    <li class="folderClosed" id="5">400_Konzepte</li>
</ul>

Help is appreciated.

Greetings from switzerland

eXe

+3  A: 

You're adding an element with an ID incorrectly here (don't add the hash to the attribute, only when making a selector):

$('#' + id).after('<ul id="#' + id + '-list">');
//should be:
$('#' + id).after('<ul id="' + id + '-list">');

A bit more efficient overall would be to do this:

success: function(data){
  var parent = $('#' + id).removeClass('folderClosed').addClass('folderOpen');
  var list = $('<ul />', { id: id + '-list' });
  $.each(data, function(){
    $('<li />', { id: this.id, "class": "folderClosed", text: this.folderName })
      .appendTo(list);
  })
  list.insertAfter(parent);
}
Nick Craver
You are so right Buddy! Sometimes the "I don't see the forrest cause of all the trees" is a perfect match!
da.eXecutoR
@da.eXecutoR - take a look at the updated version...even if you don't go this route, remove the `$('#' + id).after('</ul>');`...you're not inserting HTML as you go, you're creating complete DOM elements, so be sure to insert them in chunks that way, no begin then ending tags :)
Nick Craver
@da.eXecutoR, also do not use numeric IDs. they are invalid ..
Gaby