JSFiddle - React, Tailwind, and code Playground
by evon0306
HTML
<h1>AJAX網路連線練習</h1>
<button id="my-btn" onclick="getData()">Load Products</button>
<hr>
<ul></ul>
SCSS
*{
margin: 0;
padding: 0;
box-sizing: border-box;
list-style: none;
}
ul{
display: flex;
flex-wrap: wrap;
li{
margin: 1rem;
padding: 1.5rem;
display: flex;
flex-direction: column;
border: 1px paleturquoise solid;
border-radius: 5px;
height: 200px;
position: relative;
img{
width: 120px;
height: 120px;
object-fit: contain;
}
span{
margin: 0 auto;
text-align: center;
font-size: 20px;
padding: 3px;
}
button{
background-color: aqua;
font-size: 16px;
padding: 3px;
border-radius: 4px;
border-style: none;
position: absolute;
bottom: 1px;
right: 60px;
transition: all .2s linear;
cursor: pointer;
&:hover{
color: #d81616;
}
}
}
}
JavaScript
function getData(){
//利用fetch進行連線並取得資料
fetch('https://fakestoreapi.com/products')
.then(res=>res.json())
.then(json=>{
console.log(json);
let ul = document.querySelector('ul');
for(let i = 0; i<json.length; i++){
console.log(json[i]);
let list = document.createElement('li');
let img = document.createElement('img');
let span = document.createElement('span');
let btn = document.createElement('button');
img.src = json[i].image;
span.textContent = json[i].category;
btn.textContent = "Details";
btn.onclick = () => {
alert(json[i].id);
alert(json[i].category);
alert(json[i].description);
}
list.append(img);
list.append(span)
list.append(btn);
ul.append(list);
}
})
.catch(error => {
alert("抱歉,請稍後重新嘗試。");
})
}