如何使用JavaScript结合Tailwind CSS在DOM中渲染数组对象为独立卡片
解决数组对象渲染为Tailwind卡片的问题
嘿,我一眼就看到你代码里的小问题啦!你现在没法正确渲染每个产品卡片,核心原因是遍历数组时没有获取到当前的单个对象,而是一直在访问整个数组本身。我来帮你修正,顺便给你提几个优化点~
核心问题分析
你用itemObject.forEach(() => { ... })的时候,回调函数里没有接收当前遍历到的元素参数,导致你写的${itemObject.img}、${itemObject.title}这些都是在访问整个数组,而不是数组里的每个产品对象。
修正后的完整代码
const productsDOM = document.querySelector(`.products`); const itemObject = [{ title: "Chocolate", price: 10.99, id: 1, img: "https://images.pexels.com/photos/1055272/pexels-photo-1055272.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260" }, { title: "Whipped Cream", price: 12.99, id: 2, img: "https://images.pexels.com/photos/1055270/pexels-photo-1055270.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" }, { title: "White Frosting", price: 12.99, id: 3, img: "https://images.pexels.com/photos/1055271/pexels-photo-1055271.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260" }, { title: "Berry", price: 14.99, id: 4, img: "https://images.pexels.com/photos/3081657/pexels-photo-3081657.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260" }, { title: "Deluxe", price: 19.99, id: 5, img: "https://images.pexels.com/photos/1998634/pexels-photo-1998634.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260" }, { title: "Oreo", price: 14.99, id: 6, img: "https://images.pexels.com/photos/783274/pexels-photo-783274.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260" }]; function displayProducts() { let html = ``; // 这里添加item参数,接收当前遍历的产品对象 itemObject.forEach((item) => { html += ` <!-- 把固定的id改成动态的,确保每个卡片id唯一 --> <div id="item-${item.id}" class="bg-white rounded-lg shadow-md overflow-hidden"> <!-- 把w-screen改成w-full,避免卡片宽度超出容器 --> <img class="rounded-t-md w-full object-cover max-h-60" src="${item.img}" alt="${item.title}"> <div class="py-2 px-4 text-gray-600"> <div class="grid grid-cols-2 py-3 text-xl font-bold "> <h3>${item.title}</h3> <p class="text-right">$${item.price}</p> </div> <button data-id=${item.id} class="bg-purple-200 font-bold px-3 mt-2 text-xl py-4 w-full rounded-md transition-all hover:bg-purple-300">Purchase</button> </div> </div> `; }); productsDOM.innerHTML = html; } // 别忘了调用这个函数哦! displayProducts();
主要改动点说明
- 遍历参数添加:在
forEach的回调里加上(item),这样每次循环都能拿到当前的产品对象,用item代替原来的itemObject来访问属性。 - 动态id设置:把卡片的
id="item-1"改成id="item-${item.id}",保证每个卡片的id都是唯一的,方便后续操作。 - 图片样式优化:把
w-screen改成w-full,避免图片宽度超出父容器;同时给img添加了alt="${item.title}",提升可访问性。 - 调用函数:最后加上
displayProducts(),确保页面加载时执行渲染逻辑。
额外提示(针对新手)
别忘了在你的HTML里准备好对应的容器,建议给它加上Tailwind的布局类,让卡片排列更美观:
<div class="products grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 p-4"></div>
这样修改后,每个产品都会生成独立的Tailwind卡片,数据也能正确显示啦~
内容的提问来源于stack exchange,提问作者OrangeSoLlama
相关产品推荐
相关产品推荐

