JSFiddle - React, Tailwind, and code Playground
HTML
<button class="load">Load Products</button>
<hr>
<ul class="lists"></ul>
CSS
* {
margin: 0;
padding: 0;
list-style: none;
}
.load {
font-size: 24px;
background-color: bisque;
padding: 5px 10px;
border-radius: 8px;
cursor: pointer;
transform: scale(.8);
transition: scale .2s;
}
.load:hover {
transform: scale(1);
}
ul {
display: grid;
grid-template-columns: repeat(auto-fill, 200px);
grid-gap: 20px;
justify-content: space-evenly;
}
li {
display: flex;
flex-direction: column;
}
li button {
width: 100px;
margin: 0 auto;
background-color: transparent;
border-radius: 8px;
font-size: 18px;
cursor: pointer;
transition: background .2s;
margin-top: 5px;
}
li button:nth-of-type(2):hover {
background-color: #f77;
}
li button:hover {
background-color: bisque;
}
span {
text-align: center;
font-size: 18px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
img {
width: 200px;
height: 200px;
vertical-align: middle;
}
JavaScript
const loadButton = document.querySelector('.load');
const lists = document.querySelector('.lists');
loadButton.onclick = () => {
const url = 'https://fakestoreapi.com/products';
fetch(url)
.then(res=>res.json())
.then(items=> {
for (const item of items) {
const li = document.createElement('li');
const div = document.createElement('div');
const img = document.createElement('img');
const span = document.createElement('span');
const detailButton = document.createElement('button');
const deleteButton = document.createElement('button');
span.textContent = item.title;
detailButton.textContent = 'Detail';
deleteButton.textContent = 'Delete';
img.src = item.image;
detailButton.onclick = () => {
alert(item.id);
alert(item.category);
alert(item.description);
}
deleteButton.onclick = () => {
const target = event.target;
fetch(`https://fakestoreapi.com/products/${item.id}`, {
method: 'DELETE',
})
.then(res => res.json())
.then(result => {
target.closest('li').remove();
})
.catch(error => {
alert('請稍後再試。')
})
}
div.append(img);
li.append(div);
li.append(span);
li.append(detailButton);
li.append(deleteButton);
lists.append(li);
}
})
.catch(error => {
alert('抱歉,請稍後重新嘗試。')
})
}