仅获取轮播中选定的选项

Get only the selected options in the carousel

我有一个 owl 轮播,我有这个结构:

<div id="comidas" class="owl-carousel owl-theme">
    <a class="item opcion" >
        <img class="img" src = "/path/to/image.jpg" alt = "Image Name" item-id="2" >
    </a >
    <a class="item opcion" >
        <img class="img" src = "/path/to/image.jpg" alt = "Image Name" item-id="3">
    </a >
</div>

当我点击其中一项时,我将 class clicked 添加到 a 元素,如下所示:

$(document).ready(function() {

    $("#comidas").owlCarousel({
        items : 10
    });

    $('.opcion').on('click', function(event){
        var $this = $(this);
        if($this.hasClass('clicked')){
            $this.removeAttr('style').removeClass('clicked');
            $this.children('img').removeClass('selected-option');
        } else{
            $this.addClass('clicked');
            $this.children('img').addClass('selected-option');
        }
    });

});

我想知道的是,如何仅在视图中的特定元素之后使用 clicked 项目制作新的轮播?

我当时的想法是循环遍历 div 中的所有元素,然后 .insertAfter 新轮播中的一个元素...但是如何?

使用 $(".clicked") returns 具有 class "clicked" 的元素数组。有了这个,你可以制作另一个轮播并循环返回数组并使用 .append(element) 将每个点击的图像添加到新的轮播中。

假设您想在单击按钮时添加那些 clicked 项,您可以遍历这些项并将其添加到所选元素。我在 here 上做了一个类似的案例,希望对你有帮助。

<div id="source">
    <!-- assuming this is your carousel -->
    <div class="option" ><a>1</a></div>
    <div class="option" ><a>2</a></div>
    <div class="option" ><a>3</a></div>
</div>
<input type="button" id="btn-execute" value="execute" />

jQuery

$(".option").on("click",function(){
    //this works like your code above
    var $this = $(this);
    if($this.hasClass('clicked')){
        $this.removeClass('clicked');
    } else{
        $this.addClass('clicked');
    }
});

$("#btn-execute").click(function(){
    var btn_element = $(this);
    //this is how you loop through your item and add it to a specific element
    $(".option").each(function(){
        if($(this).hasClass("clicked")){
            $("<div>"+$(this).html()+"</div>").insertAfter(btn_element);
        }
    });
});