Event delegation - dynamically generated content

73 views Asked by At

Because I'm generating my content dynamically, and it doesn't exists in the document until the scripts execute, normal element selectors don't apply.

<div class="list">
    //generated elements within here
    <p data-key="0" >List Item 1</p>
    <p data-key="1">List Item 2</p>
    //generated elements within here
</div>

So this does not work(note this is the same idea as above just with different names):

Category = 0;

$(".list > p").click(function(){
    var thisKey = $(this).data("key");
    for (var i = 0; i < ServiceArray[Category][thisKey][2][1][1].length; i++) {

        var listId = ServiceArray[Category][thisKey][2][1][i][2];
        var listTitle = ServiceArray[Category][thisKey][2][1][i][0];
        var List = "";

        for (var x = 0; x < ServiceArray[Category][thisKey][2][1][i][2].length; x++) {
            var Time = ServiceArray[Category][thisKey][2][1][i][2][x][3];
            var Content = ServiceArray[Category][thisKey][2][1][i][2][x][0];
            var Hours = ServiceArray[Category][thisKey][2][1][i][2][x][4];
            List += '<div class="li"><div class="selection"></div><p data-time="' + Time + '">' + Content + '<span class="orange"> ('+ Hours +'Hrs)</span></p></div>';
        }

        $(".layer4").append('<div id="' + listId + '" class="listContainer"><h2>' + listTitle + '</h2><div class="ListWrapper">' + List + '</div></div>');
    }
});

Instead, I have to use

$(".dropdown-service").on("click" ,"p",function () {
    //all the stuff up there, in here, except in here, I can't use $(this).data("key") to get my array keys.
});

So how can I select the elements to use their attached data in the function?

Remember, $(".list > p") won't successfully select the element, since it was not generated until after the document loaded. I don't fully understand this yet, but in a previous question, it was explained as being the issue; this is a secondary issue, that arose from that question's solution.

Here is that question.

Here is a JSFiddle.

0

There are 0 answers