如何使用JS批量提取swiper三张特殊轮播slide的aria-label对应编号
你可以直接用jQuery自带的$.map方法遍历选中的元素集合,快速生成目标数组,代码如下:
var activeslides = $('.swiper-slide-prev,.swiper-slide-active,.swiper-slide-next'); var numactivesslides = $.map(activeslides, function (el) { const ariaLabel = $(el).attr('aria-label'); // 截取空格前的编号部分转数字,也可以用ariaLabel.split(' ')[0]写法更简洁 const slideNum = parseInt(ariaLabel.substring(0, ariaLabel.indexOf(' '))); return slideNum; });
执行后numactivesslides就会是你要的[3,4,5]格式的数组,数组顺序和元素在DOM中的排列顺序一致,刚好对应前一张、激活态、后一张的编号。
如果想用原生forEach实现,可以先把jQuery对象集合转为普通数组再遍历:
var activeslides = $('.swiper-slide-prev,.swiper-slide-active,.swiper-slide-next'); var numactivesslides = []; Array.from(activeslides).forEach(function (el) { const ariaLabel = el.getAttribute('aria-label'); const slideNum = parseInt(ariaLabel.split(' ')[0]); numactivesslides.push(slideNum); });
内容的提问来源于stack exchange,提问作者sprea
相关产品推荐
相关产品推荐

