Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 如何获取特定元素的索引值_Jquery - Fatal编程技术网

Jquery 如何获取特定元素的索引值

Jquery 如何获取特定元素的索引值,jquery,Jquery,如何获取特定元素的索引值。我使用了index(),但没有得到索引值。可能语法不对 <div>click me</div> <div class="test">test</div> (正如@axel.michel在评论中提到的,每个方法都已经包含一个计数器参数,在这种情况下,您不需要使用index方法) 你可以用 $(document).ready(function(){ $('div').each(function(index){

如何获取特定元素的索引值。我使用了
index()
,但没有得到索引值。可能语法不对

 <div>click me</div>
 <div class="test">test</div>

(正如@axel.michel在评论中提到的,每个方法都已经包含一个计数器参数,在这种情况下,您不需要使用index方法)

你可以用

$(document).ready(function(){
    $('div').each(function(index){ 
        if($(this).hasClass('test')){
            alert(index);
        }
    });
});


您想根据什么检查
测试
?班名?文本值?等等,你读过吗?您的
索引
将始终在给定html中返回0。测试类的div位于索引1处。我只需要索引值1@Daniel:在大多数现代编程环境中,第一个元素的索引为0,而不是1.var test=$('div.test');var指数=$(“div”).指数(测试);each方法已经包含一个计数器参数,在这种情况下不需要使用index方法。看这个演示:@axel.michel你完全正确。。我更新了我的答案
$(document).ready(function(){
    $('div').each(function(index){ 
        if($(this).hasClass('test')){
            alert(index);
        }
    });
});
$(document).ready(function(){
        $('div').each(function(){ 
            if($(this).hasClass('test')){
                alert($(this).index());
            }
        });
    });