首页 > 解决方案 > 让“点击”事件侦听器执行的问题

问题描述

所以我有三个独特的按钮,它们用自己独特的事件侦听器进程编码。但是,当我单击它们时,它们都不会执行。

index.html 代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Ghost Bear Pizza is a fictional pizza restaurant chain with the mission of service only the most exotic ingredients and toppings for their pizza.">
    <!-- <link rel="stylesheet" type="text/css" href="vendors/css/ionicons.min.css"> -->
    <link rel="stylesheet" type="text/css" href="styles.css">
    <link rel="stylesheet" type="text/css" href="queries.css">
    <title>Welcome to Ghost Bear Pizza</title>
</head>
<body>
    <header>
        <nav>
            <div class="nav__logo">
                <img src="icons/pizza-logo.svg" alt="Company Logo" class="logo" />
            </div>
            <div class="nav">
                <!-- <div class="row"> -->
                    <!-- <div>Icons made by <a href="" title="xnimrodx">xnimrodx</a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a></div> -->

                    <div class="nav__bar">
                        <ul class="nav__bar__ul">
                                <li>
                                    <a href="#">About Us</a>
                                </li>

                                <li>
                                    <a href="#">Menu</a>
                                </li>

                                <li>
                                    <a href="#">Locations</a>
                                </li>

                                <li class="cart">
                                    <a href="cart.html">
                                        <ion-icon name="cart-outline"></ion-icon>:<span>0</span>
                                    </a>
                                </li>
                        </ul>
                    </div>
                <!-- </div> -->
            </div>
        </nav>
        <div class="header__company-name">
            <div class="header__company-name__content">
            <h1>Ghost Bear Pizza</h1>

            <a href="#" class="btn btn-order">Order Now</a>
            </div>
        </div>
    </header>

    <section class="about">
        <h2><span class="section-dash">&mdash;</span> About Us <span class="section-dash">&mdash;</span></h2>
        <p>
            For years, the Ghost Bear Pizza Founders would get together at their local tabletop gaming store on every Thursday night of the week to play their session of Battletech.  Each week, they would order a cheese pizza from the local restaurant.  However, the Founders were never satisfied with the toppings that the restaurant offered, so they would always cook their own ingredients and add it to the ordered pizza.
            <br />
            <br />
            So one night, one of the Founders came up with an idea to have the three of them open up their own pizza restaurant.  There, they would use nothing but the most rare and exotic pizza ingredients and toppings that could be offered.  Extra spicy pepperoni, chorizo, savory pineapple (that's right....SAVORY pineapple).  You name it, they had it.  And that was how the first ever Ghost Bear Pizza was born in Noblesville, IN.
            <br />
            <br />
            For the next thirty years, Ghost Bear Pizza built three more restaurants throughout the northern-Indianapolis area.  Along the way, they came up with the idea of building a small section within each of their restaurants where customers could bring in their own ingredients, cook them right there in the store (under proper supervision), and use those ingredients for their own pizza meals that they would order at that restaurant.
            <br />
            <br />
            <span class="about_large">Ghost Bear Pizza locations are independently, locally-owned and operated.</span>
            <br />
            <span class="about_small">All prices are subject to change at any time.  Ghost Bear Pizza is not a registered trademark.  Seriously.  I made it up just for this website!</span>
        </p>
    </section>

    <section class="menu">
        <h2>
            <span class="section-dash">&mdash;</span> Menu <span class="section-dash">&mdash;</span>
        </h2>

        <ul class="menu-food clearfix">
            <h3>Pizzas:</h3>
            <li>
                <figure class="menu-photo">
                    <img src="img/pepperoni-min.jpg" alt="Spicy Pepperoni Pizza" />
                    <div class="menu-name"><strong>Spicy Pepperoni</strong></div>
                </figure>
            </li>
            <li>
                <figure class="menu-photo">
                    <img src="img/chorizo-min.jpg" alt="Chorizo Pizza" />
                    <div class="menu-name"><strong>Zesty Chorizo</strong></div>
                </figure>
            </li>
            <li>
                <figure class="menu-photo">
                    <img src="img/pineapple-min.jpg" alt="Savory Pineapple Pizza" />
                    <div class="menu-name"><strong>Savory Pineapple</strong></div>
                </figure>
            </li>
            <li>
                <figure class="menu-photo">
                    <img src="img/alphastrike-min.jpg" alt="The Alpha Strike" />
                    <div class="menu-name"><strong>"The Alpha Strike"</strong></div>
                </figure>
            </li>
        </ul>
        <ul class="menu-food clearfix">
            <h3>Appetizers:</h3>
            <li>
                <figure class="menu-photo">
                    <img src="img/breadsticks-min.jpg" alt="Breadsticks" />
                    <div class="menu-name"><strong>Breadsticks</strong></div>
                </figure>
            </li>
            <li>
                <figure class="menu-photo">
                    <img src="img/stuffedbreadsticks-min.jpg" alt="Stuffed Breadsticks" />
                    <div class="menu-name"><strong>Stuffed Breadsticks</strong></div>
                </figure>
            </li>
            <li>
                <figure class="menu-photo">
                    <img src="img/cheesebread-min.jpeg" alt="Garlic Cheese Bread" />
                    <div class="menu-name"><strong>Garlic Cheese Bread</strong></div>
                </figure>
            </li>
            <li>
                <figure class="menu-photo">
                    <img src="img/poppers-min.jpg" alt="Chorizo-stuffed Jalapeno Poppers" />
                    <div class="menu-name"><strong>Chorizo-stuffed Jalapeno Poppers</strong></div>
                </figure>
            </li>
        </ul>
    </section>

    <section class="locations">
        <h2>
            <span class="section-dash">&mdash;</span> Locations <span class="section-dash">&mdash;</span>
        </h2>
        <div class="location__img-container">
            <figure class="location__image">
                <img src="img/noblesvillemini.jpg" alt="Noblesville" />
                <h4>12345 Kerensky Way<br />Noblesville, IN 46060</h4>
            </figure>
            <figure class="location__image">
                <img src="img/broadripplemini.jpg" alt="Broad Ripple" />
                <h4>24680 Jorgensson Blvd.<br />Broad Ripple, IN 46220</h4>
            </figure>
            <figure class="location__image">
                <img src="img/carmelmini.jpg" alt="Carmel" />
                <h4>13579 Tseng Court<br />Carmel, IN 46069</h4>
            </figure>
            <figure class="location__image">
                <img src="img/kokomomini.jpg" alt="Kokomo" />
                <h4>54321 Tukayyid St.<br />Kokomo, IN 46901</h4>
            </figure>
        </div>
    </section>

    <section class="order">
        <h2>
            <span class="section-dash">&mdash;</span> Place an order <span class="section-dash">&mdash;</span>
        </h2>

            <br />
            <h3 class="food-header">Pizzas:</h3>
                <div class="pizza-container">
                    <div class="order-pizza">
                        <div class="order-pizza-item">
                            <figure class="order-photo">
                                <img src="img/pepperoni-min.jpg" alt="Spicy Pepperoni Pizza" />
                                <div class="order-name">Spicy Pepperoni</div>
                                <button class="btn-form-order">Add to Cart</button>
                            </figure>
                        </div>
                        <div class="order-pizza-item">
                            <figure class="order-photo">
                                <img src="img/chorizo-min.jpg" alt="Chorizo Pizza" />
                                <div class="order-name">Zesty Chorizo</div>
                                <button class="btn-form-order">Add to Cart</button>
                            </figure>
                        </div>
                        <div class="order-pizza-item">
                            <figure class="order-photo">
                                <img src="img/pineapple-min.jpg" alt="Savory Pineapple Pizza" />
                                <div class="order-name">Savory Pineapple</div>
                                <button class="btn-form-order">Add to Cart</button>
                            </figure>
                        </div>
                        <div class="order-pizza-item">
                            <figure class="order-photo">
                                <img src="img/alphastrike-min.jpg" alt="The Alpha Strike" />
                                <div class="order-name">"The Alpha Strike"</div>
                                <button class="btn-form-order">Add to Cart</button>
                            </figure>
                        </div>
                    </div>
                </div>

            <h3 class="food-header">Appetizers:</h3>

                <div class="appetizer-container">
                    <div class="order-appetizer">
                        <div class="order-appetizer-item">
                            <figure class="order-photo">
                                <img src="img/breadsticks-min.jpg" alt="Breadsticks" />
                                <div class="order-name">Breadsticks</div>
                                <button class="btn-form-order">Add to Cart</button>
                            </figure>
                        </div>
                        <div class="order-appetizer-item">
                            <figure class="order-photo">
                                <img src="img/stuffedbreadsticks-min.jpg" alt="Stuffed Breadsticks" />
                                <div class="order-name">Stuffed Breadsticks</div>
                                <button class="btn-form-order">Add to Cart</button>
                            </figure>
                        </div>
                        <div class="order-appetizer-item">
                            <figure class="order-photo">
                                <img src="img/cheesebread-min.jpeg" alt="Garlic Cheese Bread" />
                                <div class="order-name">Garlic Cheese Bread</div>
                                <button class="btn-form-order">Add to Cart</button>
                            </figure>
                        </div>
                        <div class="order-appetizer-item">
                            <figure class="order-photo">
                                <img src="img/poppers-min.jpg" alt="Chorizo-stuffed Jalapeno Poppers" />
                                <div class="order-name">Chorizo-stuffed Jalapeno Poppers</div>
                                <button class="btn-form-order">Add to Cart</button>
                            </figure>
                        </div>
                    </div>
                </div>

                <div class="checkout">
                    <button class="btn-checkout">Checkout</button>
                </div>
    </section>

    <footer>
        <p>&copy; Chris Rumler<span class="copyright"></span></p>
        <ion-icon name="logo-facebook"></ion-icon>
        <ion-icon name="logo-twitter"></ion-icon>
        <ion-icon name="logo-instagram"></ion-icon>
        <p>Please visit my LinkedIn profile: <a href="https://www.linkedin.com/in/chrisrumler/">linkedin.com/in/chrisrumler/</a></p>
    </footer>

    <script src="script.js"></script>
    <script src="https://unpkg.com/ionicons@5.4.0/dist/ionicons.js"></script>
</body>
</html>

购物车.html 代码:

<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <link rel='stylesheet' href='styles.css'>
    <title>Ghost Bear Pizza Shopping Cart</title>
</head>
<body>
    <header class='cart-header'>
        <div class='overlay'>
            <nav class='cart-nav'>
                <h2>Your current order</h2>
                <ul>
                    <li><a href='index.html'>Back to Home</a></li>
                    <li class='cart'>
                        <a href='cart.html' class='cart-link'>
                            <ion-icon name='cart-outline'></ion-icon>:<span>0</span>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
    </header>

    <div class='products-container'>
        <div class='product-header'>
            <h5 class='product-title'>FOOD ITEM</h5>
            <h5 class='product-price'>PRICE</h5>
            <h5 class='product-quantity'>QUANTITY</h5>
            <h5 class='product-total'>TOTAL</h5>
        </div>
        <div class='products'>

        </div>
    </div>

    <footer>
        <p>&copy; My Name<span class="copyright"></span></p>
        <ion-icon name="logo-facebook"></ion-icon>
        <ion-icon name="logo-twitter"></ion-icon>
        <ion-icon name="logo-instagram"></ion-icon>
        <p>Please visit my LinkedIn profile: <a href="https://www.linkedin.com">linkedin.com</a></p>
    </footer>
    <script src='https://unpkg.com/ionicons@5.4.0/dist/ionicons.js'></script>
    <script src='script.js'></script>
</body>
</html>

Script.js 文件:

'use strict';

//! Updates Copyright year within Footer section
let copyrightYear = new Date().getFullYear();
document.querySelector('.copyright').innerHTML = ' | ' + copyrightYear;

//! Grabs the "Add to Cart" button
let carts = document.querySelectorAll('.btn-form-order');

//! Stores catalog of pizza products for sale
let products = [
    {
        name: 'Spicy Pepperoni Pizza',
        tag: 'pepperoni-min',
        price: 20,
        inCart: 0
    },
    {
        name: 'Zesty Chorizo Pizza',
        tag: 'chorizo-min',
        price: 20,
        inCart: 0
    },
    {
        name: 'Savory Pineapple Pizza',
        tag: 'pineapple-min',
        price: 20,
        inCart: 0
    },
    {
        name: 'The Alpha Strike',
        tag: 'alphastrike-min',
        price: 30,
        inCart: 0
    },
    {
        name: 'Breadsticks',
        tag: 'breadsticks-min',
        price: 5,
        inCart: 0
    },
    {
        name: 'Stuffed Breadsticks',
        tag: 'stuffedbreadsticks-min',
        price: 8,
        inCart: 0
    },
    {
        name: 'Garlic Cheese Bread',
        tag: 'cheesebread-min',
        price: 7,
        inCart: 0
    },
    {
        name: 'Chorizo Stuffed Jalapeno Poppers',
        tag: 'poppers-min',
        price: 10,
        inCart: 0
    }
];

for (let i = 0; i < carts.length; i++) {
    carts[i].addEventListener('click', () => {
        cartNumbers(products[i]);
        totalCost(products[i]);
    })
};

//! Function that checks the number of products currently in cart and updates the Cart button's number value on page load
function onLoadCartNumbers() {
    let productNumbers = localStorage.getItem('cartNumbers');

    if (productNumbers) {
        document.querySelector('.cart span').textContent = productNumbers;
    }
};

//! Local Storage function for cart
function cartNumbers(product, action) {
    let productNumbers = localStorage.getItem('cartNumbers');

    productNumbers = parseInt(productNumbers);

    let cartItems = localStorage.getItem('productsInCart');

    cartItems = JSON.parse(cartItems);

    if (action == 'decrease') {
        localStorage.setItem('cartNumbers', productNumbers - 1);
        document.querySelector('.cart span').textContent = productNumbers - 1;
    } else if (productNumbers) {
        localStorage.setItem('cartNumbers', productNumbers + 1);
        document.querySelector('.cart span').textContent = productNumbers + 1;
    } else {
        localStorage.setItem('cartNumbers', 1);
        document.querySelector('.cart span').textContent = 1
    }
    setItems(product);
};

function setItems(product) {
    let cartItems = localStorage.getItem('productsInCart');
    cartItems = JSON.parse(cartItems);
    console.log('My cartItems are', cartItems);

    //! If statement starts adding to inCart value for each product item
    if (cartItems !== null) {

        //! This checks to see if a second (or more) product is clicked on and, if so, adds it to the 'product' object

        if (cartItems[product.tag] == undefined) {
            cartItems = {
                ...cartItems,
                [product.tag]: product
            }
        }
        cartItems[product.tag].inCart += 1;
    } else {
        product.inCart = 1;

        cartItems = {
            [product.tag]: product
        }
    }
    localStorage.setItem('productsInCart', JSON.stringify(cartItems));
};

//! Function that calculates total cost of product(s) added to cart
function totalCost(product, action) {
    let cartCost = localStorage.getItem('totalCost');

    if (action == 'decrease') {
        cartCost = parseInt(cartCost);

        localStorage.setItem('totalCost', cartCost - product.price);
    } else if (cartCost != null) {
        cartCost = parseInt(cartCost);
        localStorage.setItem('totalCost', cartCost + product.price);
    } else if (!product.price){
        cartCost = parseInt(cartCost);
        cartCost = 0;
    } else {
        localStorage.setItem('totalCost', product.price);
    }
};

function displayCart() {
    let cartItems = localStorage.getItem('productsInCart');
    let productContainer = document.querySelector('.products');
    let cartCost = localStorage.getItem('totalCost');

    cartItems = JSON.parse(cartItems);

    if (cartItems && productContainer) {
        productContainer.innerHTML = '';
        Object.values(cartItems).map(item => {
            productContainer.innerHTML += `
            <div class='product'>
                <ion-icon name='close-circle'></ion-icon>
                <img src='./img/${item.tag}.jpg' />
                <span class='cart-item-label'>${item.name}</span>
            </div>
            <div class='product-price'>$${item.price}.00</div>
            <div class='product-quantity'>
                <ion-icon class='decrease' name='remove-circle'></ion-icon>
                <span>${item.inCart}</span>

                <ion-icon class='increase' name='add-circle'></ion-icon>
            </div>
            <div class='product-total'>
                $${item.inCart * item.price}.00
            </div>
            `;
        });

        productContainer.innerHTML += `
            <div class='basketTotalContainer'>
                <h4 class='basketTotalTitle'>Basket Total</h4>
                <h4 class='basketTotal'>$${cartCost}.00</h4>
            </div>
        `
        deleteButtons();
        manageQuantity();
    }
};

function deleteButtons() {
    let deleteButtons = document.querySelectorAll('.product ion-icon');
    let productNumbers = localStorage.getItem('cartNumbers');
    let cartCost = localStorage.getItem('totalCost');
    let cartItems = localStorage.getItem('productsInCart');
    cartItems = JSON.parse(cartItems);
    let productName;

    for(let i = 0; i < deleteButtons.length; i++) {
        deleteButtons[i].addEventListener('click', () => {
            productName = deleteButtons[i].parentElement.textContent.toLocaleLowerCase().replace(/ /g,'').trim();
           
            localStorage.setItem('cartNumbers', productNumbers - cartItems[productName].inCart);
            localStorage.setItem('totalCost', cartCost - (cartItems[productName].price * cartItems[productName].inCart));

            delete cartItems[productName];
            localStorage.setItem('productsInCart', JSON.stringify(cartItems));

            displayCart();
            onLoadCartNumbers();
        })
    }
};

function manageQuantity() {
    let decreaseButtons = document.querySelectorAll('.decrease');
    let increaseButtons = document.querySelectorAll('.increase');
    let cartItems = localStorage.getItem('productsInCart');
    cartItems = JSON.parse(cartItems);
    let currentQuantity = 0;
    let currentProduct = '';

    for (let i = 0; i < decreaseButtons.length; i++) {
        decreaseButtons[i].addEventListener('click', () => {
            currentQuantity = decreaseButtons[i].parentElement.querySelector('span').textContent;
            console.log(currentQuantity);
            currentProduct = decreaseButtons[i].parentElement.previousElementSibling.previousElementSibling.querySelector('span').textContent.toLowerCase().replace(/ /g, '');
            console.log(currentProduct);

            if (cartItems[currentProduct].inCart > 1) {
                cartItems[currentProduct].inCart -= 1;
                cartNumbers(cartItems[currentProduct], 'decrease');
                totalCost(cartItems[currentProduct], 'decrease');
                localStorage.setItem('productsInCart', JSON.stringify(cartItems));
                displayCart();
            }
        })
    };

    for (let i = 0; i < increaseButtons.length; i++) {
        increaseButtons[i].addEventListener('click', () => {
            currentQuantity = increaseButtons[i].parentElement.querySelector('span').textContent;
            console.log(currentQuantity);
            currentProduct = increaseButtons[i].parentElement.previousElementSibling.previousElementSibling.querySelector('span').textContent.toLowerCase().replace(/ /g, '').trim();
            console.log(currentProduct);


            cartItems[currentProduct].inCart += 1;
            cartNumbers(cartItems[currentProduct]);
            totalCost(cartItems[currentProduct]);
            localStorage.setItem('productsInCart', JSON.stringify(cartItems));
            displayCart();
        })
    };
};

onLoadCartNumbers();
displayCart();

样式.css 代码:

@import url('https://fonts.googleapis.com/css2?family=Quicksand:wght@300;400;700&display=swap');

/* Ghost Bear blue: #2376bc | rgb(35, 118, 188) */

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html,
body {
    font-family: 'Quicksand', sans-serif;
    font-weight: 400;
    font-size: 20px;
    color: #414141;
    text-rendering: optimizeLegibility;
}

.cart-header {
    background-image: url('img/cart-header.jpg');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    height: 150px;
    position: relative;
    color: white;
}

.overlay {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    height: 100%;
    right: 0;
    bottom: 0;
    padding: 0;
    margin: 0;
    background-color: rbga(10,10,10.0.3);
}

.cart-nav {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    z-index: 2;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 50px 60px 0 60px;
}

.cart-nav li {
    list-style: none;
    display: inline-block;
    padding-right: 10px;
    padding-left: 10px;
}

.cart-nav li span {padding-left: 5px;}

.cart-link {
    padding: 5px;
    background-color: white;
    text-decoration: none;
}

.cart ion-icon {
    vertical-align: bottom;
    font-size: 20px;
    padding-right: 5px;
}

.products-container {
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
    margin: 0 auto;
    margin-top: 50px;
    padding-bottom: 100px;
    max-width: 1000px;
}

.products-container ion-icon {
    font-size: 25px;
    color: #2376bc;
    margin: 0 10px;
    cursor: pointer;
}

.product-header {
    width: 100%;
    max-width: 1000px;
    display: flex;
    border-bottom: 4px solid #2376bc;
    margin: 0 auto;
}

.product {
    width: 45%;
    display: flex;
    justify-content: right;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #2376bc;
}

.product-title {width: 45%;}

.product-price {
    width: 15%;
    border-bottom: 1px solid #2376bc;
    display: flex;
    align-items: center;
}

.product-quantity {
    width: 30%;
    border-bottom: 1px solid #2376bc;
    display: flex;
    align-items: center;
}

.product-total {
    width: 10%;
    border-bottom: 1px solid #2376bc;
    display: flex;
    align-items: center;
}

.cart-item-label {font-size: 90%}

.products {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
}

.products img {width: 75px;}

.basketTotalContainer {
    display: flex;
    justify-content: flex-end;
    width: 100%;
    padding: 10px 0;
}

.basketTotalTitle {width: 30%;}

.basketTotal {width: 10%;}

这是我的购物车的屏幕截图,其中每个产品都添加到购物车中,以防它可以帮助某人完全想象我希望它如何工作:

Cart.html 的快照

标签: javascriptlocal-storageaddeventlistener

解决方案


我想到了。我需要更改我的 .trim() 方法,以便它以事件处理程序需要的方式匹配我的产品名称。


推荐阅读