JSFiddle - React, Tailwind, and code Playground
HTML
<h1 style="text-align: center;">JavaScript 系列五:第6課 ── 學會 AJAX 與各種 HTTP 請求方法</h1>
<button id="load">Load Products</button>
<hr>
<ul></ul>
CSS
* {
padding: 0;
margin: 0;
list-style-type: none;
}
ul {
display: flex;
flex-wrap: wrap;
}
ul li {
width: 25%;
padding: 50px;
box-sizing: border-box;
}
ul li .img-box {
width: 100%;
height: 200px;
}
ul li .img-box img {
width: 100%;
height: 100%;
object-fit: contain;
transition: 0.5s;
}
ul li .img-box img.active {
transform: scale(1.25);
}
ul li .txt-box {
margin-top: 20px;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
height: 200px;
}
ul li .txt-box span {
text-align: center;
line-height: 1.5;
font-size: 18px;
}
ul li .txt-box button {
font-size: 16px;
display: inline-block;
padding: 10px 20px;
color: #fff;
background-color: rgba(100, 100, 255, 1);
border: none;
border-radius: 10px;
cursor: pointer;
}
#load {
display: block;
padding: 5px 10px;
margin: 10px auto;
cursor: pointer;
}
JavaScript
let loadBtn = document.querySelector("#load");
let ul = document.querySelector("ul");
load.onclick = function loading() {
fetch("https://fakestoreapi.com/products")
.then((res) => res.json())
.then((json) => {
for (const product of json) {
let list = document.createElement("li");
let imgBox = document.createElement("div");
imgBox.classList.add("img-box");
let txtBox = document.createElement("div");
txtBox.classList.add("txt-box");
let img = document.createElement("img");
img.src = product.image;
let productNameSpan = document.createElement("span");
productNameSpan.textContent = product.title;
let detailBtn = document.createElement("button");
detailBtn.textContent = "Details";
detailBtn.onclick = function showDetails() {
alert(product.id);
alert(product.category);
alert(product.description);
};
let deleteBtn = document.createElement("button");
deleteBtn.textContent = "Delete";
deleteBtn.onclick = function deleteProduct() {
let id = product.id;
let idList = event.target.closest("li");
fetch("https://fakestoreapi.com/products/" + id, {
method: "DELETE"
})
.then((res) => res.json())
.then((json) => {
idList.remove();
})
.catch((error) => {
alert("請稍後再試");
});
};
ul.append(list);
list.append(imgBox);
list.append(txtBox);
imgBox.append(img);
txtBox.append(productNameSpan);
txtBox.append(detailBtn);
txtBox.append(deleteBtn);
detailBtn.addEventListener("mouseover", function() {
img.classList.add("active");
});
detailBtn.addEventListener("mouseout", function() {
img.classList.remove("active");
});
...