我开发了以下javascript代码,
function find_closest_a(el) {
while (el) {
if (el.tagName === 'A') return el;
el = el.parentNode;
}
}
var images = document.querySelectorAll('.album-img');
for (var i = 0; i < images.length; i++) {
var aElment = find_closest_a(images[i]);
if (aElment) {
aElment.href = images[i].src;
}
}
for (var x = 0; x < address.length; x++) {
var dynamic_address = "<div class='col-lg-6 col-md-6 col-sm-6 col-xs-12 mob-no-pad'>" +
"<div class='address-blk'><span>1</span><p class='store-name'>" + storename[x] + ",</p>" +
"<address>" + address[x] + "</address>" +
"<p>Sent to : <a href=''>Email</a> | <a href=''>Text</a> | <a href=''>Get directions</a></p> </div></div>";
$("#location-address").html(dynamic_address);
}
我的问题是当我运行地址数组的代码最终地址时,storename数组的最终值显示在location-address div(只有一个div)中。 Address.length具有动态值。如何显示所有三个(任意数字)div,而不仅仅是一个div?
答案 0 :(得分:0)
问题是因为您正在使用html()
方法,该方法将覆盖元素中的任何先前值,因此仅显示循环的最后一个元素。您需要使用append()
代替:
$("#location-address").append(dynamic_address);
如果需要,您可能还需要使用empty()
清除#location-address
的内容,然后再通过循环更新内容。
答案 1 :(得分:0)
var dynamic_address="";
for (var x = 0; x < address.length; x++) {
dynamic_address += "<div class='col-lg-6 col-md-6 col-sm-6 col-xs-12 mob-no-pad'>" +
"<div class='address-blk'><span>1</span><p class='store-name'>" + storename[x] + ",</p>" +
"<address>" + address[x] + "</address>" +
"<p>Sent to : <a href=''>Email</a> | <a href=''>Text</a> | <a href=''>Get directions</a></p> </div></div>";
}
$("#location-address").html(dynamic_address);