jquery - 组合 Bootstrap 4 下拉和折叠时的奇怪行为
问题描述
我正在以一种非常简单的方式组合 Bootstrap 下拉菜单和折叠。从下拉列表中选择条目时,应在隐藏当前折叠项后显示相应的折叠项。所以我.collapse('hide')
用来隐藏当前项目,等待hidden.bs.collapse
被解雇然后.collapse('show')
显示新的折叠项目。奇怪的是,在从下拉列表中选择一个条目几次(6-10 次)后,该类show
被添加到两个折叠项,然后添加到三个,依此类推。我真的看不出我做错了什么。
这是一个带有要重现的代码的代码笔。
任何帮助表示赞赏:)
解决方案
好的,一次又一次地在单击项目时添加事件处理程序绝不是一个好主意;)
我首先拥有的是:
;(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 );
推荐阅读
- javascript - 应用我为数组的每个元素创建的方法
- azure - 将 bak 文件还原到 Azure SQL PAAS 数据库?
- swift - 使用未解析的标识符“Form”
- c++ - 加速简单 Eigen 程序的基本方法
- influxdb - 如何查询所有 InfluxDB _internal 数据库测量?
- android - 如何修复工作不正常的工作经理类?
- delphi - 如何从 Delphi 执行 WSL
- angular - Angular 库导出了一些意想不到的类
- azure-devops - 如何授予 Azure Pipelines 对网络资源的访问权限?
- matlab - 从 .svg 在 Matlab 中导入贝塞尔曲线坐标时出现问题