简体   繁体   English

如何从api查看项目并将项目添加到购物车

[英]how to view items from api and add item to cart

im fetching items image , name ,price ,about from API i fetched each item and added it in html tag the problem when i press add to cart button nothing adding 即时消息从API中获取项目图像,名称,价格,关于我我获取了每个项目并将其添加到html标签中,当我按下添加到购物车按钮时没有问题

i tried onclick function on the button and call item by id 我尝试了按钮上的onclick函数,并通过id调用了项

html page HTML页面


     <div id="api-1" class="images full">


            </div>

js file js文件


window.onload = function(){
 const name = document.getElementById('api-1');
 const tableItems = document.getElementById('item');
 const cartContent = document.getElementsByClassName('table-cart');




 fetch('https://us-central1-guitar-chord-de94e.cloudfunctions.net/products')
.then(response => response.json())
.then(items => { 
    let html = '';
    items.forEach(item =>{
      // console.log(item.items.name)

      html += `
      <div class="container">
      <img src=${item.items.image} class="item">

      <div class="overlay">
        <p style="color:white">${item.items.name}</p>
        <p style="color: white;font-weight: bold;font-size: 17px">price: ${item.items.price}</p>
        <div style="margin-top:60px;">
      <button  onclick="addToCart()"  style="background-color: gold;margin:0%;">add <img width="16px" src="./image/icons/shopping-cart.png" alt=""></button>
      </div>
    </div>

    </div> 

      `;
      name.innerHTML= html;
    })
});



}


function addToCart(){
  fetch('https://us-central1-guitar-chord-de94e.cloudfunctions.net/products')
.then(response => response.json())
.then(sys => { 

    sys.forEach(item =>{ console.log(item.sys);

});
});
}

You have to pass the id, button click handler like in below code. 您必须像下面的代码那样传递id,按钮单击处理程序。

<button onclick="addToCart(${item.sys.id})" style="background-color: gold;margin:0%;"></button>

Here's a working pen. 这是一支工作笔。 https://codepen.io/anon/pen/jjojVm https://codepen.io/anon/pen/jjojVm

I am capturing id of the clicked item in addToCart function. 我在addToCart函数中捕获单击项的ID。 Using that id, you can maintain a cart in the same page or you can goto to different page passing the same id in URL depending on your requirement. 使用该ID,您可以在同一页面中维护购物车,也可以根据需要转到URL中传递相同ID的其他页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM