单击后重定向到另一个 .html,从对象中提取数据

Redirection after click to another .html, pulling data from object

提问人:Zed 提问时间:10/13/2023 最后编辑:Heretic MonkeyZed 更新时间:10/13/2023 访问量:57

问:

我有一个对象(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')

enter image description here

JavaScript HTML CSS 对象

评论

0赞 adampweb 10/13/2023
该语句仅适用于模块import
0赞 Mark Schultheiss 10/13/2023
请更新到底什么不起作用:“不知道为什么,但这不起作用”;- 我注意到,如果我正确阅读了这篇文章,你没有指向第二页的链接
0赞 Nick Parsons 10/13/2023
你的错误意味着 ,这意味着要么不是你认为的那样。查看这些日志记录为您提供了什么,并检查 中是否是有效的索引。itemundefineddataididdata
0赞 Heretic Monkey 10/13/2023
请注意,代码目前依赖于微弱的平衡;这始终与数组中对象的索引匹配。在我看来,这是灾难的根源。我会更改为 be 并检查 null,如果未找到,则显示错误。iddataconst item = data[id];const item = data.find(el => el.id === id)item
0赞 Heretic Monkey 10/13/2023
此外,在 HTML 中,将锚元素放在按钮中是无效的。要么使用普通的锚点(如果需要,可以使用CSS将其样式设置为按钮)或按钮(尽管我建议不要这样做,因为锚点用于单击时导航的元素)。

答: 暂无答案