Search code examples
jquerynestedsetappendlive

problem with appending new uls


I have da database with categories using nested sets.

i have a function, that should list me all the categories one level beneath a certain category.

when the document loads, the starting category is "1". this works. but when i click on a list item - to do the same with this items id as startingpoint, nothing happens. the data is passed to the document, but jquery isn't able to apend the list items to the created ul.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="JavaSkript/jquery-1.4.4.min.js"></script>
    <style>
        ul.kategorien{ background: #FECA40; float: left;}
    </style>
</head>
<body>
    <div id="kategorien_auflisten" style="background-color: #ffffff;">

    </div>
    <div id="error"></div>
</body>
</html>

<script type="text/javascript">
function auflisten(start) {
    $("div#kategorien_auflisten").append("<ul class='kategorien' id='" + start + "'></ul>")

    jQuery.getJSON("Datenbankabfragen/kategorien_auflisten.php", {
        startknoten: start
    }, function(data) {
        if(data != "") {
            $.each(data, function(i,data){
                $("ul#"+start).append("<li class='' id='" + data.Kategorie_Nr + "'>" + data.Name + "</li>");
            });
        }
        else {
            $("div#error").text("Die Kategorien können leider nicht aufgelistet werden.");
        }
    });
}

$(document).ready(function() {
    auflisten(1);
});

$("li").live("click", function() {
    auflisten($(this).attr("id"));
});
</script>

I hope anyone could help. Thank you!


Solution

  • I think I see a couple of issues.

    First, you're taking the ID from a li element:

    $("li").live("click", function() {
        auflisten($(this).attr("id"));  // ID of the <li>
    });
    

    ...passing it to auflisten:

    function auflisten(start) {
    

    ...the assigning that ID to a ul element:

    .append("<ul class='kategorien' id='" + start + "'></ul>")
    

    So now it would seem that you have 2 elements with the same ID, which is invalid.

    So it seems likely that when you try to select the new ul element from the DOM using that ID, the selection will fail:

     $("ul#"+start) // Trying to select based on a non-unique ID will cause problems.
    

    Second, it seems that you're using numeric IDs. This is not valid in HTML4, and can cause similar selection problems.