简体   繁体   中英

How to access dynamically added elements and their IDs using jQuery or JavaScript in general?

I have a list of restaurants, and each restaurant has its articles. For each restaurant representation in the list I have a button. By clicking this button, I want to redirect the user to the page with articles of the specific restaurant.

The restaurant list is dynamically generated via jQuery. I tried giving the button an ID with the restaurant name, but whatever button I click, it gives me the name of the first restaurant in the list. Here is the code:

    $(document).ready(function() {    
        var rests = [];

        $.get({
            url: "/WebProjekat/rest/restaurants",
            success: function(restaurants) {
                rests = restaurants;
                alert("restaurantssss");
                alert(restaurants[0].name);
                var arrayLength = restaurants.length;
                for(var i=0; i < arrayLength; i++) {
                    $("#restaurantList").append("<div class=\"row\">" + 
                    "<div class=\"card\" style=\"width: 18rem;\">" + 
                    "<img class=\"card-img-top\" src=\"restaurant.jpg\"" +
                    "alt=\"Card image cap\"><div class=\"card-body\">" + 
                    "<h5 class=\"card-title\">" + restaurants[i].name + "</h5>" + 
                    "<p class=\"card-text\">" + restaurants[i].category + "</p>" +
                    "<button id=\"" + restaurants[i].name + "\" class=\"btn\">" + 
                    "See articles" + "</button>" + "</div></div></div>");
                }
            }
        })
        $("#addRestaurant").click(function(){
            window.location.href = "addRestaurants.html";
        });

        $("#addArticle").click(function(){
            window.location.href = "addArticles.html";
        });

        $("#restaurantList").on('click', '.btn', function() {
            //$("")
            var id = $("#restaurantList .row .card .card-body .btn").attr("id");
            alert(id);
            window.location.href = "articles.html?restaurant="+id;
        });
    })

As you can see in the for loop I give an appropriate ID to every button, and then in the delegate function I access the button through links with the parent. But like I said earlier, whatever button is clicked, the output is the name of the first restaurant in the list. It's possible I am misinterperting how the delegate function works.

Does anyone have any idea why this isn't working? And if this way is dead end, please provide me an alternative solution. Thanks in advance

Replace this

$("#restaurantList").on('click', '.btn', function() {
     //$("")
     var id = $("#restaurantList .row .card .card-body .btn").attr("id");
     alert(id);
     window.location.href = "articles.html?restaurant="+id;
});

With below one and it should work

$("body").on('click', '.btn', function() {
     //$("")
     var id = $(this).attr("id");
     alert(id);
     window.location.href = "articles.html?restaurant="+id;
});

This is beacuse dynamically added element should reference body or document to delegate click event on dynamic id/class. Also this keyword will corresponds to current clicked button.

When trying to get the id of the button

var id = $("#restaurantList .row .card .card-body .btn").attr("id");

this will cycle through the page and return the first element of #restaurantList .row .card .card-body .btn which is why it doesn't matter what button you click on, you will always get the same result.Thn the click by using $(this) you are referring to the button that has been clicked.

hope this helps.

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