Can you specify a “data-target” for Bootstrap which refers to a sibling DOM element without using an ID?

前端 未结 7 822
长发绾君心
长发绾君心 2020-12-13 13:04

I am dynamically adding Collapsable elements to a page. Bootstrap uses the \"data-target\" attribute to specify which element the collapse toggle applies to.

From

7条回答
  •  暖寄归人
    2020-12-13 13:53

    @merv's solution didn't work for me in IE9 and below, since the collapsible state wasn't available unless you clicked at each item once. It did work fine in Firefox and Chrome though. So after two clicks, everything would work.

    What I did was set a .collapse-next class to the triggering elements, then force their ul siblings to collapse with toggle set to false:

    $(".collapse-next").closest('li').each(function(){
      if ($(this).hasClass('active')) {
        // pop up active menu items
        $(this).children("ul").collapse('show');
      } else {
        // just make it collapsible but don't expand
        $(this).children("ul").collapse({ toggle: false });
      }
    });
    

    This is for actually toggling the menu state:

    $('.collapse-next').click(function(e){
      e.preventDefault();
      $(this).parent().next().collapse('toggle');
    });
    

    It seems that using data- attributes is a somewhat more modern and cleaner approach, but for old browsers working with classes and jQuery seems to do the job as well.

提交回复
热议问题