[英]Owl Carousel 2 remove specific item
我使用 Owl Carousel 2,我的 HTML 代碼如下。 每個圖像的右上角都會有一個小“x”圖標,單擊時我希望將圖像從輪播中刪除。
第一次點擊時,效果很好,因為傳遞給“remove_image”function的索引是正確的。 但是在第二次單擊另一個圖像時,索引將不再正確。
例如:第一次點擊image2.jpg,傳遞給“remove_image”的索引為1,這是正確的。 從 Owl Carousel 2 中正確刪除的圖像。
第二次點擊image4.jpg,傳遞給“remove_image”的索引是3。這個索引是錯誤的。 這是因為 Owl Carousel 2 在 image2 被移除后更新了。 image4.jpg 現在的正確索引是 2。
我該如何解決這個問題? 請幫忙。 謝謝。
<div class="owl-carousel owl-theme">
<div class="item"><img src="/image1.jpg" /><a onclick="remove_image(0);"><i class="icon-remove"></i></a></div>
<div class="item"><img src="/image2.jpg" /><a onclick="remove_image(1);"><i class="icon-remove"></i></a></div>
<div class="item"><img src="/image3.jpg" /><a onclick="remove_image(2);"><i class="icon-remove"></i></a></div>
<div class="item"><img src="/image4.jpg" /><a onclick="remove_image(3);"><i class="icon-remove"></i></a></div>
<div class="item"><img src="/image5.jpg" /><a onclick="remove_image(4);"><i class="icon-remove"></i></a></div>
<div class="item"><img src="/image6.jpg" /><a onclick="remove_image(5);"><i class="icon-remove"></i></a></div>
</div>
function remove_image(index) {
$('.owl-carousel').owlCarousel('remove', index).owlCarousel('update');
}
您在調用remove_image
時使用固定索引。 由於這些不會隨着項目的刪除而更新,因此這些固定索引變得不准確。
一個快速(但不一定是最好的)解決方法是使用this
而不是固定索引來傳遞錨元素本身,然后讓您的 function 從中派生目標索引:
<div class="owl-carousel owl-theme">
<div class="item"><img src="/image1.jpg" /><a onclick="remove_image(this);"><i class="icon-remove"></i></a></div>
<!-- more slides -->
</div>
function remove_image(trigger) {
var $item = $(trigger).closest('.owl-item');
var index = $item.closest('.owl-stage').children().index($item);
$item.closest('.owl-carousel').owlCarousel('remove', index).owlCarousel('update');
}
.owl-stage
和.owl-item
是初始化 owl carousel 時添加的幾個元素中的一部分。 .owl-stage
位於用戶提供的容器和項目之間,包裝這些項目。 .owl-item
包裝每個項目並且是.owl-stage
的孩子。
參考:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.