如何将参数传递给函数并使用html

时间:2019-06-21 22:23:22

标签: javascript html arrays parameter-passing

我正在用本地存储的javascript制作购物车,上周我已经问过类似的问题,我部分解决了我的问题,但我不得不休息一下,现在我回来了,但我一直被困住在这个问题上持续了几天。我以为这样可以,但是不行。而且没有任何错误。

function addToCartClicked(event) {
    var button = event.target
    var shopItem = button.parentElement.parentElement
    var title = shopItem.getElementsByClassName('shop-item-title')[0].innerText
    var price = shopItem.getElementsByClassName('price')[0].innerText
    var imageSrc = shopItem.getElementsByClassName('image')[0].src
    console.log(title, price, imageSrc)
    //var Item =
    //{
        //title: title,
        //price: price,
        //image: imageSrc

        //var title = title;
        //var price = price;
        //var imageSrc = imageSrc
    //}
    //var item = new Item(title, price, imageSrc)
    //var item = new Item(title, price, imageSrc)

    var product = [
        {
            "title": title,
            "price": price,
            "image": imageSrc
        }
    ]
    var pods = JSON.parse(localStorage.getItem("item")) || []
    pods.push(product)
    localStorage.setItem("item" ,JSON.stringify(pods))
    displayCart(title, price, imageSrc)
    saveCart()
}

function loadCart() {
    let listItems = JSON.parse(localStorage.getItem("item"));
    for (var i = 0; i < localStorage.length; i++){
        displayCart(listItems[i]);
    }
}


function displayCart(listItems) {
    //var item = JSON.parse(localStorage.getItem("item"))[0]
    //pods[0].title = title;
    //pods[0].price = price;
    //pods[0].imageSrc = imageSrc;
    listItems.title = title;
    listItems.price = price;
    listItems.imageSrc = imageSrc;
    var cartRow = document.createElement('div')
    cartRow.classList.add('cart-row')
    var cartItems = document.getElementsByClassName('cart-items')[0]
    var cartRowContents = `
        <div class="cart-row">
            <div class="cart-column cart-item" style="padding-top: 1%"><img class="image" style="width: 25%;" src="${imageSrc}" alt="" ><h2 style="padding-left: 5%">${title}</h2></div>
            <div class="cart-column cart-price" style="padding-top: 1%"><h2 class="price">${price}</h2></div>
            <form class="cart-column cart-quantity"><input class="quantity" type="number" id="number" value="1" style="width: 15%; margin-left: auto; margin-right: 60%" /></form>
            <span style="margin-top: auto; margin-bottom: auto;">
                  <button class="btn btn-primary shop-item-button " type="button">Remove</button>
            </span>
        </div>`

    cartRow.innerHTML = cartRowContents
    cartItems.append(cartRow)
    cartRow.getElementsByClassName('btn-primary')[0].addEventListener('click', RemoveCartItem)
    saveCart()
}

我希望显示购物车能够检索标题,价格,imageScr,然后将其显示在页面上的HTML中。

0 个答案:

没有答案