简体   繁体   English

通常如何使用jQuery或JavaScript访问动态添加的元素及其ID?

[英]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. 餐厅列表是通过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. 我尝试为按钮提供带有餐厅名称的ID,但是无论我单击哪个按钮,它都会为我提供列表中第一家餐厅的名称。 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. 如您所见,在for循环中,我为每个按钮提供了一个适当的ID,然后在委托函数中,我通过与父级的链接访问该按钮。 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. 这是因为动态添加的元素应引用正文或文档来委托动态ID /类上的click事件。 Also this keyword will corresponds to current clicked button. 关键字也将对应于当前单击的按钮。

When trying to get the id of the button 尝试获取按钮的ID时

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. 这将循环浏览页面并返回#restaurantList .row .card .card-body .btn的第一个元素,这就是为什么无论单击哪个按钮都一样,您将始终获得相同的结果。使用$(this)指的是已单击的按钮。

hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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