我有一个显示产品列表的页面。用户可以选择要订购的产品数量,然后单击订购按钮。这应该在 Cookie 中放置对数量和产品 ID 的引用。然而目前按钮
甚至还没有被注册。当我点击它时什么也没有发生。
如果我将按钮放在 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 ?>
这是单击按钮
时要执行的代码
$("#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。如果你想将事件分配给多个对象,你必须使用类。
当您使用 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"/>
关于javascript - JQuery 未注册按钮点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24116012/