Javascript 如何获取特定类属性的html元素中的数字?

Javascript 如何获取特定类属性的html元素中的数字?,javascript,jquery,html,count,Javascript,Jquery,Html,Count,使用Javascript,我希望在所有可能的元素中找到包含“swiper active switch”属性的元素,并将其返回给包含它的span元素 <span class="swiper-pagination-switch"></span> <span class="swiper-pagination-switch"></span> <span class="swiper-pagination-switch"></span>

使用Javascript,我希望在所有可能的元素中找到包含“swiper active switch”属性的元素,并将其返回给包含它的span元素

<span class="swiper-pagination-switch"></span>
<span class="swiper-pagination-switch"></span>
<span class="swiper-pagination-switch"></span>
<span class="swiper-pagination-switch"></span>
<span class="swiper-pagination-switch swiper-visible-switch swiper-active-switch"></span>
<span class="swiper-pagination-switch"></span>`
将给出结果,即4,因为它是0索引的,如果需要5,只需加1


如果循环是实现活动所必需的,并且与代码更相似,则应尝试以下操作:

var total = $('span').length;
var searchClass="swiper-pagination-switch";
var searchIndex;

//there is an index return by jQuery.each method
$('span').each(function(index){
    if($(this).hasClass(searchClass)){
        searchIndex = index;
    }
});
console.log('total:'+total+' active:'+searchIndex);

你们真的需要知道它在源代码的哪一行,还是只需要知道它是第五个跨度?仅仅因为这两个元素在您非常小的示例中恰好相同,并不意味着总是这样,或者源代码中的这一行表示元素在DOM中的位置。我只想知道这是第五个跨度。是否有包含这些跨度的父元素?在同一个父元素之前还有其他元素吗?父元素是我得到的结果“-1”。@searchforit Demo添加,检查它。“total”和“searchIndex”未定义。对于未定义的total,我键入了一个错误“lenght”->“length”。对于未定义的searchIndex,可能在启动each函数时,代码中不存在该类。在循环中添加一个“console.log($(this.attr('class'));”,以确保.ok有效。但是“total”的结果为9,“active”的结果为8。$('span')在页面中检测到span,您应该改为执行更具体的操作,如$('.pagination span')
$('span.swiper-pagination-switch').index($('.swiper-visible-switch'))
var total = $('span').length;
var searchClass="swiper-pagination-switch";
var searchIndex;

//there is an index return by jQuery.each method
$('span').each(function(index){
    if($(this).hasClass(searchClass)){
        searchIndex = index;
    }
});
console.log('total:'+total+' active:'+searchIndex);