如何在Bootstrap轮播slid.bs.carousel事件中获取指示器的data-value
如何在Bootstrap轮播的slid.bs.carousel事件中获取指示器的自定义data-value属性?
嗨,这问题其实不难解决,Bootstrap轮播的切换逻辑里已经帮我们做好了状态同步,直接利用这个特性就能拿到你要的data-value啦!
首先先确认你的指示器HTML结构大概是这样的(我假设你已经加好了自定义的data-value属性):
<div id="myCarousel" class="carousel slide" data-bs-ride="carousel"> <!-- 轮播指示器 --> <div class="carousel-indicators"> <button type="button" data-bs-target="#myCarousel" data-bs-slide-to="0" class="active" data-value="first-slide" aria-current="true"></button> <button type="button" data-bs-target="#myCarousel" data-bs-slide-to="1" data-value="second-slide"></button> <button type="button" data-bs-target="#myCarousel" data-bs-slide-to="2" data-value="third-slide"></button> </div> <!-- 轮播内容区 --> <div class="carousel-inner"> <div class="carousel-item active"> <img src="..." class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="..." class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="..." class="d-block w-100" alt="..."> </div> </div> </div>
接下来分两种情况给你写代码:
原生JavaScript版本
在slid.bs.carousel事件触发后(这个事件是轮播切换完成才会触发),我们只需要找到当前带有active类的指示器按钮,就能拿到它的data-value:
// 获取轮播容器元素 const carousel = document.getElementById('myCarousel'); // 监听轮播切换完成事件 carousel.addEventListener('slid.bs.carousel', function() { // 找到当前激活的指示器按钮 const activeIndicator = this.querySelector('.carousel-indicators button.active'); // 两种方式获取data-value:用getAttribute或者dataset API const targetValue = activeIndicator.dataset.value; // 或者 const targetValue = activeIndicator.getAttribute('data-value'); // 这里就可以用拿到的值做你需要的操作了 console.log('当前轮播对应的data-value:', targetValue); });
jQuery版本(如果你用的是jQuery版Bootstrap)
代码会更简洁一点,利用jQuery的选择器和data()方法:
$('#myCarousel').on('slid.bs.carousel', function() { const targetValue = $(this).find('.carousel-indicators button.active').data('value'); console.log('当前轮播对应的data-value:', targetValue); });
原理很简单:Bootstrap在切换轮播时,会自动给当前选中的指示器按钮添加active类,所以我们只要在切换完成后定位到这个元素,就能轻松拿到你自定义的属性值啦!
内容的提问来源于stack exchange,提问作者FireFoxII
相关产品推荐
相关产品推荐

