jQuery.on不在不同的div内调用

时间:2019-03-06 21:18:22

标签: javascript jquery html

当我将#myCart桌子放在身体内时,物品会被添加到购物车,并且“删除”按钮也能正常工作

jsfiddle.net/Ldnjf0by

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>The Boutique</title>
        <link rel="icon" href="./img/favicon.png">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <link rel="stylesheet" href="./css/index.css">
        <link rel="stylesheet" href="./css/layout.css">
        <script type="text/javascript" src="./js/jquery-3.3.1.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
        <link href="https://fonts.googleapis.com/css?family=Laila" rel="stylesheet">
    </head>
    <body>
        <div class="logoRow">
            <div>
                <img style="width: 80px" src="./img/logo.png">
            </div>
            <div class="topSideBar">
                <div>
                    <ul>
                        <li>Cart</li>
                        <li id="cart_container">
                            <div id="cart_counter">0</div>

                            <div id="cart_button" class="image"></div>

                            <div id="cart_items">
                                <h3>Cart</h3>
                                <div id="cart-container" style="height:300px;">

                                </div>
                            </div>
                        </li>
                        <li><a href="#">Womens</a></li>
                        <li><a href="#">Mens</a></li>
                        <li><a href="#">Boys</a></li>
                        <li><a href="#">Girls</a></li>
                        <li><a href="#">Sign in</a></li>
                        <li><a href="#">Register</a></li>
                    </ul>
                </div>
            </div>
        </div>

        <div id="main-container">
            <div class="container">
                <p class="item">Soccer Ball</p>
                <p class="price">30</p>
                Qty <input type="number" class="qty" value="1" min="1">
                <button class="add">Add to cart</button>
            </div>
            <div class="container">
                <p class="item">Soccer Shoes</p>
                <p class="price">80</p>
                Qty <input type="number" class="qty" value="1" min="1">
                <button class="add">Add to cart</button>
            </div>
            <div class="container">
                <p class="item">Soccer Jersey</p>
                <p class="price">130</p>
                Qty <input type="number" class="qty" value="1" min="1">
                <button class="add">Add to cart</button>
            </div>
        </div>


        <table id="myCart" border="1">
            <tr>
                <th>Item Name</th>
                <th>Qty</th>
                <th>Price</th>
                <th>Total</th>
                <th>Remove</th>
            </tr>
            <tr style="display: none; border-top: 2px solid black;">
                <td colspan="3">Subtotal</td>
                <td class="right subtotal"></td>
            </tr>
        </table>

        <div class="bottomNav">
            <div class="bottomNavContents">
                <div>
                    <a href="/">Home</a>&nbsp;&nbsp;&nbsp;&nbsp;
                    <a href="/about-kfc.php">About KFC</a>&nbsp;&nbsp;&nbsp;&nbsp;
                    <a href="/contact-us.php">Contact Us</a>&nbsp;&nbsp;&nbsp;
                    <a href="#">Feedback</a>
                </div>
                <div class="socialMediaIcons">
                    <a href="#"><img style="width: 30px; height: 30px;" src="./img/fb-icon.jpg" alt=""></a>
                    <a href="#"><img style="width: 30px; height: 30px;" src="./img/instagram-icon.png" alt=""></a>
                    <a href="#"><img style="width: 30px; height: 30px;" src="./img/twitter-icon.png" alt=""></a>
                </div>
            </div>
        </div>
    </body>
    <script>
    $(document).ready(function () {

        // ANIMATEDLY DISPLAY THE NOTIFICATION COUNTER.
        $('#cart_counter').animate({ top: '-2px', opacity: 1 }, 500);

        $('#cart_button').click(function () {

            // TOGGLE (SHOW OR HIDE) NOTIFICATION WINDOW.
            $('#cart_items').fadeToggle('fast', 'linear');

            return false;
        });

        // HIDE cart_items WHEN CLICKED ANYWHERE ON THE PAGE.
        $(document).click(function () {
            $('#cart_items').hide();
        });

        $('#cart_items').click(function () {
            return false;       // DO NOTHING WHEN CONTAINER IS CLICKED.
        });

        $('.add').click(function() {

            var itemsNo = parseInt($('.itemsNo').text());
            itemsNo = itemsNo + 1;

            $('.itemsNo').text(itemsNo);

            $('#myCart tr:last').show();

            var item = $(this).siblings('.item').text();
            var price = $(this).siblings('.price').text();
            var qty = $(this).siblings('.qty').val();
            var total = price * qty;

            // to check if item exists in table
            if($("td:contains('" + item + "')").length > 0) {
                var lastQty = $("td:contains('" + item + "')").next().text();

                var accumQty = parseInt(lastQty) + parseInt(qty);

                $("td:contains('" + item + "')").siblings('.qty2').text(accumQty);

                total = price * accumQty;

                $("td:contains('" + item + "')").siblings('.total').text(total);

                var sum = 0;
                $(".total").each(function() {
                    var val = parseInt($(this).text());
                    sum += val;
                });

                $(".subtotal").text(sum);
            } else {
                $("#myCart tr:last").before(
                        "<tr>" +
                            "<td class='item_name'>" + item + "</td>" +
                            "<td class='qty2'>" + qty + "</td>" +
                            "<td class='right price2'><span class='currency'>$ </span>" + price + "</td>" +
                            "<td class='right total'>" + total + "</td>" +
                            "<td><button class='remItem' onclick='remove()'>X</button></td>" +
                        "</td>"
                );

                var sum = 0;
                $(".total").each(function() {
                    var val = parseInt($(this).text());
                    sum += val;
                });

                $(".subtotal").text(sum);
            }

            $(this).siblings('.qty').val(1);
        });

        $(document).on("click", "button.remItem" , function() {
            var totalPrice = parseInt($('.subtotal').text()) - parseInt($(this).parent().siblings('.total').text());
            $(".subtotal").text(totalPrice);
            $(this).parent().parent().remove();
        });
    });
</script>
</html>

但是,当将#myCart表放置在#cart容器中时,删除按钮将不起作用。但是所有添加到购物车的作品。是什么原因导致这种行为?

https://jsfiddle.net/Ldnjf0by/1/

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>The Boutique</title>
        <link rel="icon" href="./img/favicon.png">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <link rel="stylesheet" href="./css/index.css">
        <link rel="stylesheet" href="./css/layout.css">
        <script type="text/javascript" src="./js/jquery-3.3.1.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
        <link href="https://fonts.googleapis.com/css?family=Laila" rel="stylesheet">
    </head>
    <body>
        <div class="logoRow">
            <div>
                <img style="width: 80px" src="./img/logo.png">
            </div>
            <div class="topSideBar">
                <div>
                    <ul>
                        <li>Cart</li>
                        <li id="cart_container">
                            <div id="cart_counter">0</div>

                            <div id="cart_button" class="image"></div>

                            <div id="cart_items">
                                <h3>Cart</h3>
                                <div id="cart-container" style="height:300px;">
                                    <table id="myCart" border="1">
                                        <tr>
                                            <th>Item Name</th>
                                            <th>Qty</th>
                                            <th>Price</th>
                                            <th>Total</th>
                                            <th>Remove</th>
                                        </tr>
                                        <tr style="display: none; border-top: 2px solid black;">
                                            <td colspan="3">Subtotal</td>
                                            <td class="right subtotal"></td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </li>
                        <li><a href="#">Womens</a></li>
                        <li><a href="#">Mens</a></li>
                        <li><a href="#">Boys</a></li>
                        <li><a href="#">Girls</a></li>
                        <li><a href="#">Sign in</a></li>
                        <li><a href="#">Register</a></li>
                    </ul>
                </div>
            </div>
        </div>

        <div id="main-container">
            <div class="container">
                <p class="item">Soccer Ball</p>
                <p class="price">30</p>
                Qty <input type="number" class="qty" value="1" min="1">
                <button class="add">Add to cart</button>
            </div>
            <div class="container">
                <p class="item">Soccer Shoes</p>
                <p class="price">80</p>
                Qty <input type="number" class="qty" value="1" min="1">
                <button class="add">Add to cart</button>
            </div>
            <div class="container">
                <p class="item">Soccer Jersey</p>
                <p class="price">130</p>
                Qty <input type="number" class="qty" value="1" min="1">
                <button class="add">Add to cart</button>
            </div>
        </div>




        <div class="bottomNav">
            <div class="bottomNavContents">
                <div>
                    <a href="/">Home</a>&nbsp;&nbsp;&nbsp;&nbsp;
                    <a href="/about-kfc.php">About KFC</a>&nbsp;&nbsp;&nbsp;&nbsp;
                    <a href="/contact-us.php">Contact Us</a>&nbsp;&nbsp;&nbsp;
                    <a href="#">Feedback</a>
                </div>
                <div class="socialMediaIcons">
                    <a href="#"><img style="width: 30px; height: 30px;" src="./img/fb-icon.jpg" alt=""></a>
                    <a href="#"><img style="width: 30px; height: 30px;" src="./img/instagram-icon.png" alt=""></a>
                    <a href="#"><img style="width: 30px; height: 30px;" src="./img/twitter-icon.png" alt=""></a>
                </div>
            </div>
        </div>
    </body>
    <script>
    $(document).ready(function () {

        // ANIMATEDLY DISPLAY THE NOTIFICATION COUNTER.
        $('#cart_counter').animate({ top: '-2px', opacity: 1 }, 500);

        $('#cart_button').click(function () {

            // TOGGLE (SHOW OR HIDE) NOTIFICATION WINDOW.
            $('#cart_items').fadeToggle('fast', 'linear');

            return false;
        });

        // HIDE cart_items WHEN CLICKED ANYWHERE ON THE PAGE.
        $(document).click(function () {
            $('#cart_items').hide();
        });

        $('#cart_items').click(function () {
            return false;       // DO NOTHING WHEN CONTAINER IS CLICKED.
        });

        $('.add').click(function() {

            var itemsNo = parseInt($('.itemsNo').text());
            itemsNo = itemsNo + 1;

            $('.itemsNo').text(itemsNo);

            $('#myCart tr:last').show();

            var item = $(this).siblings('.item').text();
            var price = $(this).siblings('.price').text();
            var qty = $(this).siblings('.qty').val();
            var total = price * qty;

            // to check if item exists in table
            if($("td:contains('" + item + "')").length > 0) {
                var lastQty = $("td:contains('" + item + "')").next().text();

                var accumQty = parseInt(lastQty) + parseInt(qty);

                $("td:contains('" + item + "')").siblings('.qty2').text(accumQty);

                total = price * accumQty;

                $("td:contains('" + item + "')").siblings('.total').text(total);

                var sum = 0;
                $(".total").each(function() {
                    var val = parseInt($(this).text());
                    sum += val;
                });

                $(".subtotal").text(sum);
            } else {
                $("#myCart tr:last").before(
                        "<tr>" +
                            "<td class='item_name'>" + item + "</td>" +
                            "<td class='qty2'>" + qty + "</td>" +
                            "<td class='right price2'><span class='currency'>$ </span>" + price + "</td>" +
                            "<td class='right total'>" + total + "</td>" +
                            "<td><button class='remItem' onclick='remove()'>X</button></td>" +
                        "</td>"
                );

                var sum = 0;
                $(".total").each(function() {
                    var val = parseInt($(this).text());
                    sum += val;
                });

                $(".subtotal").text(sum);
            }

            $(this).siblings('.qty').val(1);
        });

        $(document).on("click", "button.remItem" , function() {
            var totalPrice = parseInt($('.subtotal').text()) - parseInt($(this).parent().siblings('.total').text());
            $(".subtotal").text(totalPrice);
            $(this).parent().parent().remove();
        });
    });
</script>
</html>

2 个答案:

答案 0 :(得分:2)

问题所在

$('#cart_items').click(function () {
    return false;       // DO NOTHING WHEN CONTAINER IS CLICKED.
});

在删除按钮事件之前单击return false时,此代码将#cart_items,这将停止从触发器.. [1] 删除return false

[2] 另外,请使用$(this).parent().parent().remove();

代替$(this).closest('tr').remove()

注意::使用.remove,您需要花点时间检查列表中是否只有一项才能删除总行

请参见 fiddle

答案 1 :(得分:0)

从此行中删除onClick,因为它已在代码中实现

<td><button class='remItem' onclick='remove()'>X</button></td>

此外,由于td是动态添加的,因此事件冒泡也无法正常发生。修改了点击目标以使事件起泡

已修复此https://jsfiddle.net/ujf3e42r/