所以我正在尝试构建商店功能,我想要做的是能够通过按页面上的“添加到购物车”按钮将每个对象的信息保存到存储。我想知道如何为每个“添加到购物车”按钮创建唯一ID,同时使用for循环创建如下所示的多个项目/功能框?
// temporary javascript thingy while we build the remove catalogs
var popularItems =
[
{
"itemImageSrc" : "./images/StoreProducts/StrawberryPi2ModelB.jpg",
"itemImageAlt" : "placeholder",
"itemDescription" : "<p> Strawberry Pi 3 Model B </p>",
"itemPrice" : "<p>$49.95</p>",
"itemPopular" : "true"
},
{
"itemImageSrc" : "./images/StoreProducts/StrawberryPiZero.jpg",
"itemImageAlt" : "placeholder",
"itemDescription" : "<p> Strawberry Pi Zero </p>",
"itemPrice" : "<p>$29.95</p>",
"itemPopular" : "true"
},
{
"itemImageSrc" : "./images/StoreProducts/StrawberryPiCase.jpg",
"itemImageAlt" : "placeholder",
"itemDescription" : "<p> Strawberry Pi Case </p>",
"itemPrice" : "<p>$10.95</p>",
"itemPopular" : "true"
},
{
"itemImageSrc" : "./images/StoreProducts/placeholder.png",
"itemImageAlt" : "placeholder",
"itemDescription" : "<p> Strawberry Pi Extension Kit </p>",
"itemPrice" : "<p>$149.95</p>",
"itemPopular" : "false"
}
];
document.write( '<div class="feature-container">' );
for ( var i = 0; i < popularItems.length; i++) {
if ( popularItems[i].itemPopular == "true" ) {
document.writeln('<div class="feature-box">');
document.write('<img src="');
document.writeln(popularItems[i].itemImageSrc);
document.write('" alt="');
document.write(popularItems[i].itemImageAlt);
document.writeln('">');
document.write('<div class="feature-box-model" id="var i">');
document.write(popularItems[i].itemDescription);
document.writeln('</div>');
document.write('<div class="feature-box-price">');
document.write(popularItems[i].itemPrice);
document.writeln('</div>');
document.writeln('<FORM>');
document.writeln('<INPUT TYPE="button" VALUE="Add To Cart" onclick="saveData()" id="unique">');
document.writeln('</FORM>');
document.writeln('</div>');
}
}
答案 0 :(得分:1)
你可以修改这一行:
document.writeln('<INPUT TYPE="button" VALUE="Add To Cart" onclick="saveData()" id="unique">');
是:
document.writeln('<INPUT TYPE="button" VALUE="Add To Cart" onclick="saveData()" id="item_'+i+'">');
答案 1 :(得分:0)
我假设显而易见
`for( let =0; i<n; i++ ){
let key = 'key_'+i;
....
}'
不符合您的需求?
然后一个简单的方法可能是:
`key = 'key_'+Math.random().toString().slice(2);`
`// => "key_21542707442294184"`