简体   繁体   中英

jQuery click event with parameter not working

I need some help. I am trying to iterate through some Json items, create some li's with some information from the items, but also attach click handlers for the li's, but with a value transmited as parameter.

The problem is that the last value of that parameter is set for or the li's in the list. From what i searched i understood that it has something to do with javascript closure, but can't seem to understand how to fix it.

I am using jQuery and here is the code:

for (var i = 0; i < items.length; i++)
{
    // information that will be displayed for each video
    var entry = items[i];

    var title = entry.title;
    var image = entry.thumbnail.hqDefault;
    var id = entry.id;

    var li = $("<li class='video-single'>");
    li.append("<img src='" + image + "' alt='" + title + "'>");
    li.append("<h4>" + title + "</h4>");

    $(li).click(function() {
        displayPopUp(id);
    });

    ul.append(li);
}

Could anyone please help me fix this code?

Best regards, Marius.

The issue is that JS is function scoped so the id within your closure is the last id from your for loop. To fix this use forEach so you run each iteration of your loop in a separate scope eg

items.forEach(function (el, i) {
    // information that will be displayed for each video
    var entry = items[i];

    var title = entry.title;
    var image = entry.thumbnail.hqDefault;
    var id = entry.id;

    var li = $("<li class='video-single'>");
    li.append("<img src='" + image + "' alt='" + title + "'>");
    li.append("<h4>" + title + "</h4>");

    $(li).click(function() {
        displayPopUp(id);
    });

    ul.append(li);
});

you need delegated event as elements are created dynamically, you can use class that is being added on li which is video-single :

$(document).on('click','.video-single',function() {
                        displayPopUp(id);
                    });

you can read about Delegated Events HERE

in order to bind an event to a dynamically added element you need to delegate it as below:

for (var i = 0; i < items.length; i++)
            {
                // information that will be displayed for each video
                var entry = items[i];

                var title = entry.title;
                var image = entry.thumbnail.hqDefault;
                var id = entry.id;

                var li = $("<li class='video-single'>");
                li.append("<img src='" + image + "' alt='" + title + "'>");
                li.append("<h4>" + title + "</h4>");

                $(document).bind('click',li,function() {
                    displayPopUp(id);
                });

                ul.append(li);
            }

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