Auto-generate Div Ids for Bootstrap Accordion Menu

2020-02-15 08:26发布

I am creating a side menu using bootstrap accordion collapse and making use of knockout js binding. My problem is in assigning the right HTML element ids for toggle and collapse purposes as required by bootstrap. I have though of using the $indexin knockout to autogenerate the id. But not coming right. See my code below and comments:

<div id="content" style="font-size: 8.8pt">
    <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
        <div class="panel panel-default" id="news">
            <div class="panel-heading" role="tab" id="headingOne" data-bind="foreach: accordionItems()"><!--accordionItems is an observableArray with my accordion objects. Object has a header and a list of linkitems. Each linkItem object has linkText and url-->
                <a style="text-decoration:none;" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne"><!--want to do something like: href="#"+$index-->
                    <p class="panel-title" data-bind="text: nameHead"></p>
                </a> <!--binding a collapse header here.-->
                <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne"><!--want to autogenerate the id here using knockout for reference above-->
                    <ul class="Newsbar panel-body" data-bind="foreach: list">
                        <li><a data-bind="attr: { href: url }, text: linkText"></a></li>
                    </ul>
                </div>
            </div>
        </div> 
    </div>
</div>

1条回答
时光不老,我们不散
2楼-- · 2020-02-15 09:10

well i already done something like this before hope this helps

    <div class="panel-heading" role="tab" id="headingOne" data-bind="foreach: accordionItems()">
        <a style="text-decoration:none;" data-toggle="collapse" data-parent="#accordion"  aria-expanded="true" aria-controls="collapseOne"   data-bind="attr:{href:'#collapseOne'+$index() }" >
            <p class="panel-title" data-bind="text: nameHead"></p>
        </a> <!--binding a collapse header here.-->
        <div  class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne" data-bind="attr:{id:'collapseOne'+$index()}">
            <ul class="Newsbar panel-body" data-bind="foreach: list">
                <li><a data-bind="attr: { href: url }, text: linkText"></a></li>
            </ul>
        </div>
    </div>

Let me explain here :

You just need to create dynamic id and href in oder to work with this stuff . Well lucky you have one loop over if incase there exists multiple loops use $parentContext.index() and so on .

You just need to use attr to create dynamic id and href using $index() which gives you unique id everytime it loops .

查看更多
登录 后发表回答