首页 > 解决方案 > 组合 Bootstrap 4 下拉和折叠时的奇怪行为

问题描述

我正在以一种非常简单的方式组合 Bootstrap 下拉菜单和折叠。从下拉列表中选择条目时,应在隐藏当前折叠项后显示相应的折叠项。所以我.collapse('hide')用来隐藏当前项目,等待hidden.bs.collapse被解雇然后.collapse('show')显示新的折叠项目。奇怪的是,在从下拉列表中选择一个条目几次(6-10 次)后,该类show被添加到两个折叠项,然后添加到三个,依此类推。我真的看不出我做错了什么。

这是一个带有要重现的代码的代码笔。

任何帮助表示赞赏:)

标签: jquerybootstrap-4

解决方案


好的,一次又一次地在单击项目时添加事件处理程序绝不是一个好主意;)

我首先拥有的是:

;(function ( $ ) {

$( document ).ready( function () {
    let $dd_btn = $( '.dropdown-item', '#history' );

    $dd_btn.on( 'click', function () {
        let date     = $( this ).data( 'date' ).toString(),
            $target  = $( '#date_' + date.replace('/','_') ),
            $current = $( '.history-content__single.show' );

        if ( ! $target.hasClass( 'show' ) ) {
            $current.collapse( 'hide' );
            $current.on( 'hidden.bs.collapse', function () {
                $( '.dropdown-toggle', '#history' ).text( $( this ).data( 'date' ) );
                $target.collapse( 'show' );
            } );
        }
    } );
} );
})( jQuery );

所以每次点击都会添加以下内容

$current.on( 'hidden.bs.collapse', function () {
    $( '.dropdown-toggle', '#history' ).text( $( this ).data( 'date' ) );
    $target.collapse( 'show' );
} );

工作解决方案是这样的:

;(function ( $ ) {

$( document ).ready( function () {
    let $dd_btn = $( '.dropdown-item', '#history' ),
        date = '',
        $target = '';

    $dd_btn.on( 'click', function () {
        date    = $( this ).data( 'date' ).toString(),
        $target = $( '#date_' + date.replace('/','_') );

        if ( ! $target.hasClass( 'show' ) ) {
            $( '.history-content__single.show' ).collapse( 'hide' );
        }
    } );
  
  $( '.history-content__single' ).on( 'hidden.bs.collapse', function () {
    $( '.dropdown-toggle', '#history' ).text( date );
    $target.collapse( 'show' );
  } );
} );
})( jQuery );

推荐阅读