[英]Hide AJAX Cart item numers if no item in cart
我正在努力使用一些JavaScript,以找出使其正常工作的正確方法。
我有一個按鈕,顯示購物車中的物品數量。 默認為零。 隨着物品的增加,購物車的數量也在增加。 但是起初,我不想在購物車中顯示“ 0”。
HTML:
<p id="cart_button" onclick="show_cart();">
<input type="button" id="total_items" value="0">
</p>
<div id="mycart"></div>
<div id="item_div">
<div class="items" id="item1">
<input type="button" value="Add To CART" onclick="cart('item1')">
<p>Simple Navy Blue T-Shirt</p>
<input type="hidden" id="item1_name" value="ITEM-ID1">
</div>
<div class="items" id="item2">
<input type="button" value="Add To CART" onclick="cart('item2')">
<p>Trendy T-Shirt With Back Design</p>
<input type="hidden" id="item2_name" value="ITEM-ID2">
</div>
</div>
JAVASCRIPT:
$(document).ready(function() {
$.ajax({
type: 'post',
url: 'store_items.php',
data: {
total_cart_items: "totalitems"
},
success: function(response) {
document.getElementById("total_items").value = response;
}
});
});
function cart(id) {
var name = document.getElementById(id + "_name").value;
$.ajax({
type: 'post',
url: 'store_items.php',
data: {
item_name: name
},
success: function(response) {
document.getElementById("total_items").value = response;
}
});
}
function show_cart() {
$.ajax({
type: 'post',
url: 'store_items.php',
data: {
showcart: "cart"
},
success: function(response) {
document.getElementById("mycart").innerHTML = response;
$("#mycart").slideToggle();
}
});
}
我基本上希望隱藏具有0的按鈕,直到獲得值為止。 如果它回到零,我希望它再次被隱藏。 感謝您的幫助!
您可以在更新購物車時顯示/隱藏:
// Add this function
function update_cart(value) {
document.getElementById("total_items").value = response;
if (value > 0) {
// Show the cart
document.getElementById("total_items").style.display = "block";
} else {
// Hide the cart
document.getElementById("total_items").style.display = "none";
}
}
然后,當更新購物車時,您需要更改代碼:
$.ajax({
type: 'post',
url: 'store_items.php',
data: {
total_cart_items: "totalitems"
},
success: function(response) {
update_cart(response);
}
});
您可以將“更改”事件監聽器添加到此按鈕:
let totalItems = $('#total_items');
totalItems.change(function () {
if (totalItems.val() == 0) {
totalItems.hide();
}
else totalItems.show();
});
另外,您還應該在ajax的成功方法中觸發此事件:
success: function(response) {
document.getElementById("total_items").value = response;
totalItems.change();
}
最后在開始時隱藏此按鈕:
<input type="button" id="total_items" value="0" style="display: none">
檢查此工作是否在小提琴中進行: https : //jsfiddle.net/xpvt214o/771844/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.