提问人:Zed 提问时间:10/13/2023 最后编辑:Heretic MonkeyZed 更新时间:10/13/2023 访问量:57
单击后重定向到另一个 .html,从对象中提取数据
Redirection after click to another .html, pulling data from object
问:
我有一个对象(dataCenter.js),它看起来像这样:
const productSrc = 'images/Products/'
const data = [
{
id: 0,
name: 'Name of product 1',
image: `${productSrc}/${1}.jpg`,
description: 'Some description'
},
{
id: 1,
name: 'Name of product 2',
image: `${productSrc}/${2}.jpg`,
description: 'Some description'
}, etc
在我的索引 .html 上,我有一个滑动器滑块,上面有我的产品、名称和按钮的图片 查看更多。我想当用户单击“查看更多”以重定向到我创建的另一个页面产品 .html 时,它是空的,并且用户应该在完整描述下看到更大的产品名称图片。
我的刷卡滑块:
<section class="product" id="products-container">
<div class="heading">
<h3>Kozmetički aparati</31>
</div>
<div class="swiper services-slider">
<div class="swiper-wrapper">
<div class="swiper-slide slide">
<div class="image">
<img src="images/Aparati/1.jpg" alt="">
</div>
<div class="content">
<h3>7U1 WATER OXYGEN HYDRAFACIAL</h3>
<button class="myBtn btn card-btn"><a href='aparat.html?id=${item.id}'>Vidi više</a></button>
</div>
</div> etc
在我的产品.html上,我创建了一个id product-info的div,并尝试了以下代码:
import data from './dataCenter.js';
const productInfo = document.getElementById('product-info');
const urlParams = new URLSearchParams(window.location.search);
const id = urlParams.get('id');
const item = data[id];
const card = document.createElement('div');
card.classList.add("product-info-1");
const content = `
<div class="product-image">
<img src="${item.image}" class="product-thumb" alt="">
</div>
<div class="product-info-2">
<h2 class="product-brand">${item.name}</h2>
</div>
<div class='description'>${item.description}</div>
`;
card.innerHTML = content;
productInfo.appendChild(card);
在控制台上重新加载后,出现错误:
Uncaught TypeError: Cannot read properties of undefined (reading 'image')
答: 暂无答案
评论
import
item
undefined
data
id
id
data
id
data
const item = data[id];
const item = data.find(el => el.id === id)
item