簡體   English   中英

在 HTML 按鈕單擊上執行 Javascript 代碼

[英]Execute Javascript code on HTML button click

我目前正在做一個eshop。 我使用 cookies 來存放購物車。

這是我的 HTML 按鈕:

<script type="text/javascript" src="{% static 'js/store/cart.js'  %}"></script>

<button data-product={{product.id}} data-action = "add" class="btn btn1 btn-primary update-cart">Add to cart</button>

當用戶單擊此按鈕時,我想執行以下Cart.js代碼,它只是創建一個 cookie 並將產品 ID 添加到 cookie 購物車。

//here i set the cart cookie
function getCookie(name) {
    //split string and get all induvidual name=value pairs in array
    var cookieArr = document.cookie.split(';');
    //loop though array elements
    for (var i = 0; i < cookieArr.length; i++) {
        var cookiePair = cookieArr[i].split("=");

        //removing whitespace at the beginning of the cookie name and compare it with the given string
        if (name == cookiePair[0].trim()) {
            //decode cookie value and return
            return decodeURIComponent(cookiePair[1]);
        }
    }
    //return null if not found
    return null;
}

var cart = JSON.parse(getCookie('cart'));
if (cart == undefined) {
    cart = {}
    console.log("cart was created")
    document.cookie = "cart=" + JSON.stringify(cart) + ";domain=;path=/"
}
console.log("cart:", cart);


//and here i take action when the html button gets a click
var updateBtns = document.getElementsByClassName('update-cart')

for (var i = 0; i < updateBtns.length; i++) {

    updateBtns[i].addEventListener('click', function () {
            var productId = this.dataset.product
            var action = this.dataset.action
            console.log('product id:', productId, 'action:', action)
            addCookieItem(productId, action)
        
    })

}

function addCookieItem(productId, action) {
    console.log('Not logged in...')

    if (action == "add") {
        if (cart[productId] == undefined) {
            cart[productId] = { 'quantity': 1 }

        }
        else {
            cart[productId]['quantity'] += 1
        }
    }

    if (action == "remove") {
        cart[productId]['quantity'] -= 1

        if (cart[productId]['quantity'] <= 0) {
            console.log("remove item")
            delete cart[productId]
        }

    }
    console.log("Cart=", cart)
    location.reload()
    document.cookie = "cart=" + JSON.stringify(cart) + ";domain=;path=/"


我的問題是,當我單擊按鈕時,它不會采取任何行動。 怎么了?

缺少點擊處理程序。它應該是這樣的

<button onclick="addCookieItem(product.id,'add')" data-product={{product.id}} data-action = "add" class="btn btn1 btn-primary update-cart">Add to cart</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM