简体   繁体   English

单击按钮后如何获取JSON数据

[英]How to get JSON data after button click

 const Sheet = [ { "Code": "A-0-1", "UPC": "Photos/4009803054728.jpg", "Title": "USS Constitution", "Price": "$34", "InStock": "7" }, { "Code": "A-0-2", "UPC": "Photos/4009803073996.jpg", "Title": "Revell 07399 VW Samba Bus Model Kit", "Price": "$38", "InStock": "8" }, ] const productsEl = document.querySelector(".Sheet"); function getProducts() { Sheet.forEach((product) => { productsEl.innerHTML += `<div class="productContainer"> <div class="img"> <img src=${product.UPC} alt="Image Unavailable" height="170px;" width="170px"> </div> <div class="itemdesc"> <h2 class="itemName" id="itemName">${product.Title}</h2> <h4 class="price"><span id="price">${product.Price}</span></h4> <div class="desc"> <p id="desc">${product.Code}</p> </div> <div class="stock"> <p> ${product.InStock} Units</p> </div> <div class="addToCart" onclick="addToCart();"> <button id="addToCart" > Add to Cart</button> </div> </div>`; }) } getProducts(); function addToCart() { console.log(document.getElementById("itemName").innerText) }
 <div class="Sheet"> </div>

All right, the add to cart button only logs the first data in my object.好吧,添加到购物车按钮只记录我的对象中的第一个数据。 No matter which one I press it's always the first one.无论我按哪个,它总是第一个。 I tried .val and no luck.我试过 .val 并没有运气。 How can I log the item that was pressed instead?如何记录被按下的项目?

You can pass the name of product as an argument to the addToCart() function like below您可以将产品名称作为参数传递给addToCart()函数,如下所示

const Sheet = [
        {
            "Code": "A-0-1", 
            "UPC": "Photos/4009803054728.jpg",
            "Title": "U.S.S. Constitution",
            "Price": "$34",
            "InStock": "7"
        },
        {
            "Code": "A-0-2",
            "UPC": "Photos/4009803073996.jpg",
            "Title": "Revell 07399 VW Samba Bus Model Kit",
            "Price": "$38",
            "InStock": "8"
        },
    ]
const productsEl = document.querySelector(".Sheet");

function getProducts() {
    Sheet.forEach((product) => {
        productsEl.innerHTML += `<div class="productContainer">
            <div class="img">
                <img src=${product.UPC} alt="Image Unavailable" height="170px;" width="170px">
            </div>
            <div class="itemdesc">
                <h2 class="itemName" id="itemName">${product.Title}</h2>
                <h4 class="price"><span id="price">${product.Price}</span></h4>
                <div class="desc">
                    <p id="desc">${product.Code}</p>
                </div>
                <div class="stock">
                    <p> ${product.InStock} Units</p>
            </div>
            <div class="addToCart" onclick="addToCart(product.Title);">
                <button id="addToCart" > Add to Cart</button>
            </div>
    </div>`; 
    })
}
getProducts(); 

function addToCart(productTitle) {
    console.log(productTitle)
}

You have to pass the product's index as a parameter to the AddToCart() function.您必须将产品的index作为参数传递给AddToCart()函数。

Advantages of this implementation这种实施的优点

  1. Allows you to access other properties of the product's object like Price , InStock , etc.允许您访问产品对象的其他属性,例如PriceInStock等。
  2. If you change the property name of "Title" to something else, you only need to update the AddToCart function code, not the getProducts() 's AddToCart call-to-action.如果将“Title”的属性名称更改为其他名称,则只需更新AddToCart函数代码,而不需要更新getProducts()AddToCart调用操作。

Advice: You should try to avoid fetching items via html id or innerText (this was a norm a decade or more ago, not anymore).建议:您应该尽量避免通过 html idinnerText获取项目(这是十年或更长时间前的常态,现在不再)。 Try using more of data attributes尝试使用更多数据属性

 const Sheet = [ { "Code": "A-0-1", "UPC": "Photos/4009803054728.jpg", "Title": "USS Constitution", "Price": "$34", "InStock": "7" }, { "Code": "A-0-2", "UPC": "Photos/4009803073996.jpg", "Title": "Revell 07399 VW Samba Bus Model Kit", "Price": "$38", "InStock": "8" }, ] const productsEl = document.querySelector(".Sheet"); function getProducts() { Sheet.forEach((product, productIndex) => { productsEl.innerHTML += `<div class="productContainer"> <div class="img"> <img src=${product.UPC} alt="Image Unavailable" height="170px;" width="170px"> </div> <div class="itemdesc"> <h2 class="itemName" id="itemName">${product.Title}</h2> <h4 class="price"><span id="price">${product.Price}</span></h4> <div class="desc"> <p id="desc">${product.Code}</p> </div> <div class="stock"> <p> ${product.InStock} Units</p> </div> <div class="addToCart" onclick="addToCart(`+productIndex+`);"> <button id="addToCart" > Add to Cart</button> </div> </div>`; }) } getProducts(); function addToCart(productIndex) { var product = Sheet[productIndex]; console.log(product.Title); }
 <div class="Sheet"> </div>

Explanation解释

The parameters of a forEach function allows for the index of the current iteration. forEach函数的参数允许当前迭代的索引。 read more here在这里阅读更多

Try like this像这样试试

 const Sheet = [ { "Code": "A-0-1", "UPC": "Photos/4009803054728.jpg", "Title": "USS Constitution", "Price": "$34", "InStock": "7" }, { "Code": "A-0-2", "UPC": "Photos/4009803073996.jpg", "Title": "Revell 07399 VW Samba Bus Model Kit", "Price": "$38", "InStock": "8" }, ] const productsEl = document.querySelector(".Sheet"); function getProducts() { Sheet.forEach((product) => { productsEl.innerHTML += `<div class="productContainer"> <div class="img"> <img src=${product.UPC} alt="Image Unavailable" height="170px;" width="170px"> </div> <div class="itemdesc" > <h2 class="itemName" id="itemName">${product.Title}</h2> <h4 class="price"><span id="price">${product.Price}</span></h4> <div class="desc"> <p id="desc">${product.Code}</p> </div> <div class="stock"> <p> ${product.InStock} Units</p> </div> <div class="addToCart" onclick=""> <button class="addToCartBtn" id="${product.Code}"> Add to Cart</button> </div> </div>`; }) } getProducts(); var elements = document.querySelectorAll(".addToCartBtn"); elements.forEach(element => { element.addEventListener("click", function (e) { console.log(e.target.id); //other function }); });
 <div class="Sheet"> </div>

Use this instead...改用这个...

 const productsEl = document.querySelector(".Sheet"); const Sheet = [ { "Code": "A-0-1", "UPC": "Photos/4009803054728.jpg", "Title": "USS Constitution", "Price": "$34", "InStock": "7" }, { "Code": "A-0-2", "UPC": "Photos/4009803073996.jpg", "Title": "Revell 07399 VW Samba Bus Model Kit", "Price": "$38", "InStock": "8" }, ]; (function getProducts() { Sheet.forEach(product => { productsEl.innerHTML += `<!-- ${product.Title} --> <div class="productContainer"> <div class="img"> <img src="${product.UPC}" alt="${product.Title}" height="170px" width="170px"> </div> <div class="itemDesc"> <h2 class="name">${product.Title}</h2> <h4 class="price">${product.Price}</h4> <div class="desc"> <p>${product.Code}</p> </div> <div class="stock"> <p> ${product.InStock} Units</p> </div> <div class="addToCart"> <!-- This will ensure you're only getting the current product (via the button) --> <button onclick="addToCart(this)"> Add to Cart</button> </div> </div>`; }) })(); function addToCart(button) { const parent = button.closest('.productContainer'); // This will travel up the DOM chain from the button to the nearest element with `class="... productContainer ..."` const element = parent.querySelector('.name'); // This will travel back down the DOMchain to the element with `class="... name ..."` console.log(element.innerText); }
 <div class="Sheet"></div>

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

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