Search code examples
jqueryjsongetjson

jQuery doesn't find dynamically added DOM objects?


I am very new at jQuery ... I've used Javascript many times and am quite familiar with DOM manipulation but simply not the API or gears of jQuery.

I am dynamically adding DOM elements via a JSON call like so:

$(document).ready(function() {
        var url = "jsonMenuItems.js";
        $.getJSON(url, null, function(data) {
            var html = "";
            //alert(data.items);
            data = data.items;
            for (var key in data) {      
                html += "<td class=\"menuItem\"><span>" + data[key].name + "</span></td>";
            };
            $("#menuTR").html(html);
        });

        var lZeroArray = $("#menu td");
        lZeroArray.click(function() {
            $("#submenu").slideDown("fast");
        });
    });

If the TD items are on the page manually the click function slideDown works perfectly ... if I use the above code to dynamically add the TD items then the click function slideDown does not fire.

jQuery cannot find it's own added items or am I doing something wrong?


Solution

  • Take a look at jQuery live. This will let you bind events to dynamically added items.

    $("#menu td").live("click", function(){
        $("#submenu").slideDown("fast");
    });