【发布时间】:2017-03-27 15:17:04
【问题描述】:
目标
- 给每个礼物一个
data-id,一直到gifts.length(即245),这将帮助我从数组中提取相应的数据 - 找到一种更好的方法来为数组中的所有礼物重复结构
.gift结构
问题
我有一个包含 200 多个礼物的数组,它们都具有相似的结构,我一直在尝试为每个礼物赋予一个唯一的数据 ID,但我得到了数组中的最后一个 ID,这是 245
我还想知道在不必使用 handlebars.js 之类的情况下重复此结构的最佳方法是什么,我尝试过 multiplyNode,但我不确定浏览器支持与 @987654326 相比是否更好@
<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 -->
scripts.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": "-"
}
];
【问题讨论】:
-
我在使用 let 时遇到了一些奇怪的问题。您是否尝试过 var 代替?还有 $(".gift").attr("data-id", [i]);我认为您可以删除 i 周围的 []。而是像这样--> $(".gift").attr("data-id", i);
-
也许
$($(".gift")[i]).attr("data-id", i); -
@Icewine (".gift").attr("data-id", i) 不幸的是一遍又一遍地产生相同的
data-id -
@vothaison 尝试了你的推荐,它产生了一个空 id
-
console.log(gifts.length)
标签: javascript jquery arrays node.js for-loop