1
我正在構建購物車,並且在點擊添加按鈕後,物品圖像將以可視方式飛入購物車,並將從商店中移除。現在,我想在商店爲空時顯示一些html內容。我已經開始了(檢查下面的ajaxComplete函數)。您可能會看到這是一個動態內容,因此必須檢查類「item」是否存在,如果不存在,它將返回語句$(「#mobile」)。html(「商店中沒有商品」)。任何人都知道如何解決這個問題。檢查動態內容(json)的類是否仍然存在
var smartphones = [{
rom: 'rom1',
image: 'image1.jpg',
alt_image: 'alt_image1.jpg'
}, {
rom: 'rom2',
image: 'image2.jpg',
alt_image: 'alt_image2.jpg'
}];
function renderSmartphones() {
var newContent = "";
for (var i = 0; i < smartphones.length; i++) {
newContent += '<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 box item">';
newContent += '<div class="rom">' + smartphones[i].rom + '</div>';
newContent += '<img src="' + smartphones[i].image + '" class="image" alt="' + smartphones[i].alt_image + '" />';
newContent += '<button class="add-to-cart" type="button">add to cart</button>';
newContent += '</div>';
}
$("#mobile").html(newContent);
}
$(document).on("click", ".add-to-cart", function() {
\t var cart = $("#shopping-cart");
\t var item = $(this).closest(".item");
\t var imageToDrag = $(this).closest(".item").find(".image");
\t \t if(imageToDrag) {
\t \t var imageClone = imageToDrag.clone()
.offset({
top: imageToDrag.offset().top,
left: imageToDrag.offset().left
})
\t .css({
\t \t "background": "transparent",
"position": "absolute",
"height": "150",
"width": "150",
"z-index": "100"
})
.appendTo($("body"))
\t \t .animate({
\t \t \t "top": cart.offset().top -70,
\t \t \t "left": cart.offset().left -5,
\t \t \t "width": 80,
\t \t \t "height": 80
\t \t }, 1000);
\t \t setTimeout(function(){ //When the item is added to the cart, the item will be removed after 2 seconds
\t \t \t item.remove();
\t \t }, 2000);
\t \t imageClone.animate({ //image will fly to cart
"width": 0,
"height": 0
}, function() {
$(this).detach(); // removes selected element including all text and child nodes. However it keeps data and event.
});
\t }
});
$(document).ajaxComplete(function() {
\t if($("#mobile").closest(".item")) {
\t \t $("#mobile").html("");
\t } else {
\t \t $("#mobile").html("No item in store anymore");
\t }
});
renderSmartphones();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="wrapper">
<span><i id="shopping-cart" alt="shopping-cart-icon"></i></span>
<div id="mobile"></div>
</div>
</body>
是的,正是我一直在尋找。知道我在正確的軌道上,我有昨天鍵入相同的命名函數,但忘記調用函數。謝謝! –
welcome @ user7087446 ...! – vijayP