Twitter bootstrap collapse: change display of toggle button

后端 未结 10 721
有刺的猬
有刺的猬 2020-12-12 23:50

I am using Twitter Bootstrap to create collapsible sections of text. The sections are expanded when a + button is pressed. My html code as follows:

<         


        
10条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 00:13

    My following JS solution is better than the other approaches here because it ensures that it will always say 'open' when the target is closed, and vice versa.

    HTML:

    
        Open
    
    
    ...

    JS:

    $('[data-toggle-secondary]').each(function() {
        var $toggle = $(this);
        var originalText = $toggle.text();
        var secondaryText = $toggle.data('toggle-secondary');
        var $target = $($toggle.attr('href'));
    
        $target.on('show.bs.collapse hide.bs.collapse', function() {
            if ($toggle.text() == originalText) {
                $toggle.text(secondaryText);
            } else {
                $toggle.text(originalText);
            }
        });
    });
    

    Examples:

    $('[data-toggle-secondary]').each(function() {
        var $toggle = $(this);
        var originalText = $toggle.text();
        var secondaryText = $toggle.data('toggle-secondary');
        var $target = $($toggle.attr('href'));
    
        $target.on('show.bs.collapse hide.bs.collapse', function() {
            if ($toggle.text() == originalText) {
                $toggle.text(secondaryText);
            } else {
                $toggle.text(originalText);
            }
        });
    });
    
    
    
    
    
        Open
    
    
    ...

    JS Fiddle

    Other benefits of this approach:

    • the code is DRY and reusable
    • each collapse button stays separate
    • you only need to put one change into the HTML: adding the data-toggle-secondary attribute

提交回复
热议问题