[英]Using javascript/jQuery to access html elements that have ids/attributes dynamically generated with angular js
[英]How to access dynamically added elements and their IDs using jQuery or JavaScript in general?
我有一个餐厅列表,每个餐厅都有其文章。 对于列表中的每个餐厅代表,我都有一个按钮。 通过单击此按钮,我想将用户重定向到包含特定餐厅文章的页面。
餐厅列表是通过jQuery动态生成的。 我尝试为按钮提供带有餐厅名称的ID,但是无论我单击哪个按钮,它都会为我提供列表中第一家餐厅的名称。 这是代码:
$(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;
});
})
如您所见,在for循环中,我为每个按钮提供了一个适当的ID,然后在委托函数中,我通过与父级的链接访问该按钮。 但是就像我之前说的,无论单击什么按钮,输出都是列表中第一家餐厅的名称。 我可能会误解委托函数的工作方式。
有谁知道为什么这不起作用? 如果这种方式无济于事,请为我提供替代解决方案。 提前致谢
取代这个
$("#restaurantList").on('click', '.btn', function() {
//$("")
var id = $("#restaurantList .row .card .card-body .btn").attr("id");
alert(id);
window.location.href = "articles.html?restaurant="+id;
});
与下面的一个,它应该工作
$("body").on('click', '.btn', function() {
//$("")
var id = $(this).attr("id");
alert(id);
window.location.href = "articles.html?restaurant="+id;
});
这是因为动态添加的元素应引用正文或文档来委托动态ID /类上的click事件。 此关键字也将对应于当前单击的按钮。
尝试获取按钮的ID时
var id = $("#restaurantList .row .card .card-body .btn").attr("id");
这将循环浏览页面并返回#restaurantList .row .card .card-body .btn
的第一个元素,这就是为什么无论单击哪个按钮都一样,您将始终获得相同的结果。使用$(this)
指的是已单击的按钮。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.