[英]JQuery not registering Button click
我有一个页面,显示产品列表。 用户可以选择要订购的产品数量,然后单击订购按钮。 这应该在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。 如果要分配事件以乘以对象,则必须使用类。
当您使用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"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.