JQuery未注册按钮点击

JQuery not registering Button click

本文关键字:按钮 注册 JQuery      更新时间:2023-09-26

我有一个显示产品列表的页面。用户可以选择要订购的产品数量,然后点击订购按钮。这将在Cookie中放置对数量和产品ID的引用。然而,目前button甚至没有注册。当我点击它时,什么也没发生。

如果我将按钮置于foreach循环之外,则它可以工作。有人知道是怎么回事吗?

下面是产品列表的代码

    <?php if($products): ?>
                    <ul>
                    <?php foreach($products as $product): ?>
                    <h3 id="stock_code"><?= get_field('stock_code', $product->ID); ?></h3>
                    <p>Description: <?= get_field('description', $product->ID); ?></p>
                    <p>Quantity Per Pallet: <?= get_field('quantity_per_pallet', $product->ID); ?></p>
                    <!-- Quantity Dropdown -->
                    Amount <select id="order_amount<?= $product->ID; ?>" name="amt">
                        <option value="0">0</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                    </select>
                    <input type="submit" value="Add to Order" id="orderBtn"/>
                    <?php endforeach;  ?>
            </ul>
  <? endif ?>

这是点击button时要执行的代码

$("#orderBtn").click(function(event){
        //Show the order Box
        $(".order-alert").show();
        event.preventDefault();
        //Create the Array
        var productArray = [];   
        //If no Cookie exists, create one and add the Array
        if ($.cookie('order_cookie') === undefined) {
            console.log("Create a new cookie");
            $.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
        //If the Cookie already exists do this  
        } else {
            console.log("Read the cookie");
            productArray = JSON.parse($.cookie('order_cookie'));
            console.log($.cookie('order_cookie'));
            //Append items onto the Array
        }
        //Display the number of items in the Array in the Order Box
        $('#order_counter').html(productArray.length);
    });

在这件事上任何帮助我都很感激

不要在按钮上使用ID。如果你想给多个对象分配event,你必须使用class。

当你使用id选择器jQuery分配事件只给第一个对象,因为id应该是唯一的。

改变:

$("#orderBtn").click(function(event){
..
}

:

$(".orderBtn").click(function(event){
..
}

和HTML声明:

<input type="submit" value="Add to Order" id="orderBtn"/>

:

<input type="submit" value="Add to Order" class="orderBtn"/>