JSFiddle - React, Tailwind, and code Playground
by wimp9487
HTML
<button class="loading" onClick="loading()">Load Products</button>
<hr>
<ul class="list"></ul>
CSS
* {
box-sizing: border-box;
list-style: none;
}
img {
width: 100px;
height: 100px;
}
li {
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
}
span {
display: flex;
text-align: center;
}
button {
width: 50vw;
height: 25px;
border-radius: 10px;
background-color: rgb(75, 175, 175);
transition: all 0.3s;
}
button:hover {
background-color: rgb(175, 175, 75);
}
JavaScript
const loading = () => {
fetch('https://fakestoreapi.com/products')
.then(res=>res.json())
.then(json=>{
for (const product of json) {
const list = document.querySelector('.list');
const li = document.createElement('li');
const span = document.createElement('span');
const div = document.createElement('div');
const img = document.createElement('img');
const btn = document.createElement('button');
list.append(li);
li.append(div);
li.append(span);
li.append(btn);
div.append(img);
span.textContent = product.title;
img.src = product.image;
btn.textContent = 'Details';
btn.onclick = () => {
alert(product.id);
alert(product.category);
alert(product.description);
}
}
})
.catch(error => {
alert('抱歉,請稍後重新嘗試。');
})
}