How do I restrict a collapsible item to stay expan

2020-03-27 03:55发布

问题:

I am working on a mobile website and using jquerymobile. I have 4 collapsible items in an accordion. I want to have one of the items to stay expanded. If i click the expanded item, it is collapsed (i do not want to collapse this item). If i click any other collapsed item, the last expanded item is collapsed (thats ok).

I will appreciate your help. The dynamic javascript code for accordion categories is given bellow:

function create-accordion(categories)
    {
        category_array = categories;
        jQuery.each(categories, function( index, value )
        {
            var div =  '<div data-role="collapsible"  class="custom-collapsible"  ';
            if(index == 0)
                div += 'data-collapsed="false"';
            div += '>';

            div += '<h3 style:"padding:0px; margin:0px;"> ' + value.name + '</h3>\
                        <div class= "collapsable-limit-theme">\
                            <div data-role="content" style="padding:0px; margin:0px;">\
                                <div class="ui-grid-c, Grid" id="Grid' + value.id + '">\
                                </div>\
                            </div>\
                        </div>\
                    </div>';

            $($('#accord'), this).append(div);
        });

        $( "#accord" ).collapsibleset( "refresh" );
    }

and the html code

<div id="accord" data-role="collapsible-set" border-radius="0px" >
        </div>

Regards

回答1:

You need to listen to click on .ui-collapsible-heading-toggle and check if the clicked collapsible is either collapsed or expanded. If the collapsible is collapsed, it will have a class .ui-collapsibe-collapsed.

If the expanded collapsible is clicked, it will prevent collapsing itself by return false, otherwise, it will collapse all expanded ones.

$(".ui-collapsible-heading-toggle").on("click", function () {

    // clicked collaspible
    var collapsible = $(this).closest(".ui-collapsible");

    // check if its whether collapsed
    if (collapsible.hasClass("ui-collapsible-collapsed")) {

        // collapse expanded collapsibles
        $(".ui-collapsible").not(collapsible).trigger("collapse");
    } else {
        // keep expanded clicked collapsible as is
        return false;
    }
});

Demo