开发者

jquery doesn't add my list elements to a dynamic injected <ul> list

开发者 https://www.devze.com 2023-01-22 08:52 出处:网络
I really don\'t know where the fault is all about. Here is my code: $(document).ready(function(){ $(\"#folderTree > li\").live(\'click\',function(){

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.


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消