2012-05-23 37 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 
});