JSFiddle - React, Tailwind, and code Playground
HTML
<button id="load">Load Products</button>
<hr>
<ul></ul>
CSS
ul{
display: flex;
flex-wrap: wrap;
list-style: none;
}
li{
width: 200px;
margin: 0 10px;
text-align: center;
display: flex;
flex-direction: column;
justify-content: space-around;
}
span{
height: 3rem;
font-weight: 600;
}
img{
width: 100%;
height: 60%;
}
#load{
background-color: #ccc;
color: #000;
border-radius: 5px;
padding: 5px 10px;
}
li button{
display: block;
width: 80px;
margin: auto;
text-align: center;
color: #fff;
border: none;
padding: 0.5rem 1rem;
border-radius: 10px;
font-weight: 700;
cursor: pointer;
}
.details-btn{
background-color: #060;
}
.delete-btn{
background-color: #f00;
}
JavaScript
const loadBtn=document.querySelector("#load");
loadBtn.onclick=()=>{
fetch('https://fakestoreapi.com/products')
.then(function(res){
return res.json();
}).then(function(data){
for(const products of data){
const ul=document.querySelector("ul");
const li=document.createElement("li");
const span=document.createElement("span");
const img=document.createElement("img");
const detailsBtn=document.createElement("button");
const delBtn=document.createElement("button");
console.log(products);
ul.append(li);
li.append(img);
li.append(span);
li.append(detailsBtn);
li.append(delBtn);
img.src=products.image;
span.textContent=products.title;
detailsBtn.textContent="Details";
detailsBtn.className="details-btn";
delBtn.textContent="Delete";
delBtn.className="delete-btn";
detailsBtn.onclick=()=>{
alert(products.id);
alert(products.category);
alert(products.description);
}
delBtn.onclick=()=>{
let target=event.target;
fetch('https://fakestoreapi.com/products/6',{
method:"DELETE"
})
.then(res=>res.json())
.then(json=>{target.parentElement.remove();
})
}
}
}).catch(error=>{
alert("抱歉,請稍後重新嘗試。");
})
}