2012-05-23 38 views
2

我有相同类的div,但每个3都包装在父div中。我无法按照我想要的方式获得索引。我很抱歉,任何人都可以帮助我索引从0到8的数字..当我点击任何元素?尽管有父元素。jQuery获取元素索引,尽管包装/父元素?

这是我的完整代码,供您测试。

<div class="more-content"> 
    <div class="post">post 1</div> 
    <div class="post">post 2</div> 
    <div class="post">post 3</div> 
</div> 
<div class="more-content"> 
    <div class="post">post 4</div> 
    <div class="post">post 5</div> 
    <div class="post">post 6</div> 
</div> 
<div class="more-content"> 
    <div class="post">post 7</div> 
    <div class="post">post 8</div> 
    <div class="post">post 9</div> 
</div> 

<script type="text/javascript"> 
$(function() { 

    // navigate posts with next/prev buttons 
    $(".post").click(function(){ 
     alert($(this).index()); 
    }); 

}); 
</script> 

如果我点击我得到索引0,1,2 ..我认为是因为每个3项都裹在父母?我是新的jquery,任何帮助表示赞赏。我需要的是获得相同类的帖子的索引..说后6 =索引5 ..等等

更新 如果点击的元素是在帖子中的子锚点我怎么能得到相同的结果div和不是直接发布的div?

回答

8

尝试index方法与this作为参数:

$(".post").click(function() { 
    alert($(".post").index(this)); 
});​ 

DEMO:http://jsfiddle.net/Nryf3/

+0

也许添加'+ 1'反映岗位数量,而不是在指数div –

+0

@HunterMcMillen然后它不会是一个索引。 – VisioN

+0

我的错误我认为这是什么OP是寻找 –

0

你可以遍历所有元素标记后,并增加一个计数器,直到你找到你要找的对象,像这样:

$(".post").click(function() { 
    var counter = 0; 
    var that = this; 

    $(".post").each(function() { 
     if(that == this) break; 
     counter++; 
    } 

    // counter now equals the index of the post element out of all posts on the page 
});