JS-5-4

by jiaxin520

HTML

<!DOCTYPE html>
<html lang="zh-TW">
  <head>
    <title> JavaScript Example 5-4</title>
    <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=2">
 <link rel="stylesheet" href="">
 </head>
 <body>
<p>
<button class="load-btn">Load Products</button>
</p>
<hr>

<ul id ="list"></ul>
</body>
 <!--引用JS -->
    <script src=""></script>
    <script type="text/javascript" src=""></script>
    </html>

CSS

*{
    box-sizing: border-box;
      font-weight:bold;
}
p{
 
  display:flex;
  justify-content: center;
}
.load-btn{
  width:150px;
  font-size:28px;
  border-radius:10px;
      border:none;
      background-color:rgba(	48, 213, 200,1);
}    
.load-btn:hover{
    background-color:rgba(139, 0, 255,0.3);
}
.load-btn:active{
    transform: scale(0.7);
}
img{
  width:100px;
  height:150px;
   object-fit: contain;
}
ul{
    list-style-type: none;
    display:flex;
      flex-wrap: wrap;
       
}
li{
      display: flex;
    flex-direction: column;
   justify-content: center;
      align-items: center;
      width:30%;
      padding:5%;
      border:1px solid black;
        border-radius:10px;
}
span{
       text-align: center;
}
.list-btn{
  margin-top:15%;
  width:100px;
  font-size:18px;
    border-radius:10px;
    border:none;
      background-color:rgba(	48, 213, 200,1);
}
.list-btn:hover{
  background-color:rgba(	65, 105, 225,0.3);
}
.list-btn:active{
   transform: scale(0.7);
}

JavaScript

// fetch('https://fakestoreapi.com/products/1')
     //      .then(res=>res.json())       
       //    .then(json=>console.log(json))
 // 認識fetch 
 let loadbtn = document.querySelector('.load-btn');
 console.log(loadbtn);
 loadbtn.onclick = () => {
   fetch('https://fakestoreapi.com/products')
  .then(res=>res.json())
  .then(json=>{
 for (let items of  json){
 let lists = document.querySelector('#list');
  console.log(lists);
 let li = document.createElement('li');
 let span = document.createElement('span');
 let div = document.createElement('div');
 let img = document.createElement('img');
 let btn = document.createElement('button');
 
 lists.append(li);
 li.append(div);
 li.append(span);
 li.append(btn);
 div.append(img);
  btn.classList.add('list-btn');
 span.textContent = items.title;
 img.src = items.image;
 btn.textContent = 'detail';
 
 btn.onclick = () =>{
 alert(items.id);
 alert(items.category);
 alert(items.description);
 }
 }
 })
 }