目标
- 给每个礼物一个
data-id
1,一直到gifts.length
(即 245),这将帮助我提取相应的数组中的数据 - 找到一个更好的方法来为数组中的所有礼物重复结构
.gift
结构
问题
我有一个包含 200 多个礼物的数组,所有礼物都具有相似的结构,我一直试图给每个礼物一个唯一的数据 ID,但我得到的是最后一个 ID
在数组中,也就是245
我也想知道在不必使用 handlebars.js 之类的东西的情况下重复此结构的最佳方法是什么,我已经尝试过 multiplyNode ,但我不确定浏览器支持是否比 append
<div class="gift data-id="">
<img src="" data-original="" class="gift__image lazy">
<p class="gift__name">tk-name</p>
<p class="gift__price">tk-price</p>
<p class=""><span class="gift__description">tk-description</span> <a href="" class="gift__link">tk-url</a></p>
<div class="gift__share">
<div class="gift__icons">
<a href="" class="link--twitter" target="_blank"><i class="fa fa-twitter" aria-hidden="true"></i></a>
<a href="" class="link--facebook" target="_blank"><i class="fa fa-facebook" aria-hidden="true"></i></a>
<a href="" class="link--pinterest" target="_blank"><i class="fa fa-pinterest-p" aria-hidden="true"></i></a>
<a href="" target="_blank"><i class="fa fa-envelope" aria-hidden="true"></i></a>
</div>
</div>
<a href="" target="_blank"><button class="btn btn--buy">Buy on Amazon</button></a>
</div> <!-- .gift -->
脚本.js
// Loop over all of the gifts
for (let i = 0; i < gifts.length; i++) {
$(".gift").attr("data-id", [i]);
// Gift information from gifts.js
let giftName = $(".gift__name").html(gifts[i].Name);
let giftPrice = $(".gift__price").html(gifts[i].Price).prepend("$");
let giftDescription = $(".gift__description").html(gifts[i].Description);
let giftLink = $(".gift__link").html(gifts[i].URL);
}
function multiplyNode(node, count, deep) {
for (var i = 0, copy; i < count - 1; i++) {
copy = node.cloneNode(deep);
node.parentNode.insertBefore(copy, node);
}
}
const totalGifts = gifts.length
multiplyNode(document.querySelector('.gift'), totalGifts, true);
gifts.js(共有245个礼物)
var gifts = [
{
"ID": 1,
"Name": "Air plants",
"Price": 25,
"Description": "A small glass globe containing air plants, gravel, moss and crystals, comes in various designs and can brighten up your window or desk ($25) at Flowers and Weeds, 3201 Cherokee Street, flowersandweeds.com, which also sells monthly subscription boxes at various price points.",
"Category": "Gifts for anyone",
"Type": "Other",
"URL": "flowersandweeds.com",
"Destination": "Cherokee Street",
"Location": "Flowers and Weeds, 3201 Cherokee Street",
"Latitude": 38.59,
"Longitude": -90.2369742,
"Position": "38.5949207, -90.2369742",
"ImageURL": "-"
}
];
最佳答案
在我看来,每次执行循环时,您都将每个 id(并替换它)分配给具有 .gift 类的所有元素。 尝试仅将其分配给当前的礼物:
var gift = $($(".gift")[i]);
gift.attr("data-id", [i]);
关于javascript - 遍历数组中的项目以分配数据 ID,但仅获取数组中的最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40581062/