简体   繁体   中英

Appending ul - JQuery

I am appending a ul list and its working perfectly except when I try to append my ul table I assign a class of start-dropdownClose which is hooked to a event listener:

$(".start-dropdownClose").click(function(event){
    event.stopPropagation();
    $thisOne = $($(this).parent().attr('id'));
    alert($thisOne.selector);
    $("#" + $thisOne.selector).fadeOut();
});

Heres my method of appending:

IfpClientGui.prototype.updateFloors = function(floors){
    // updates floor list from master list of floors. 

    var ifpcg = this;
    var ifpc = ifpcg.getIfpClient();
    $("#floor_list").empty();
    $("#floor_list").append("<li class='start-dropdownClose'><a href='' onclick='return false;'>X</a></li>");

    for(var i = 0; i < floors.length; i++)
    {

        $link = $('<a href="javascript:void(0);">'+floors[i].ifpf_name+'</a>');
        $link.data("floor",floors[i]);
        $link.click(function(){         
            ifpcg.hideAllOptionBoxes();

            ifpc.displayFloor($(this).data("floor"));
            $(this).parent().find("#ifpOptionList").show();
        });

        var $floor = $('<li></li>');
        $floor.append($link);
        ifpcg.updateOptions(floors[i].groups,$floor);
        $("#floor_list").append($floor);

    }

}

Any thoughts or suggestions as to why this is happening?

The event listening is within an init class of the ifpClientGui . I even tried moving the event listening outside to a $(document).read... but with no success.

$(".start-dropdownClose") will only apply to elements with that class that exist at the time this code is executed. When you add elements with this class later on, they won't be bound to the event handler.

Try this:

$('#floor_list').on("click", ".start-dropdownClose"), function(event){
  // Your code ...
});

This means the listener is on #floor_list (which I assumed to be always present). Any click happening on the element will be registered and if it happened on the specific class, the function is triggered.

You're most likely attaching the event listener incorrectly. Remember, for dynamically added elements you have to use event delegation:

$("#floor_list").on(event_name, '.start-dropdownClose', fn);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM