2013-10-21 67 views
0

所以我可以找到一個元素是否是父元素的子元素,但我無法弄清楚如何獲取父元素中當前元素的索引。例如。我在我的頁面上摺疊了文章http://gundlach-marketing.com/dev,爲了重置頁邊距,我需要知道它們是什麼文章編號。找到父元素jquery的哪個子元素

var articleId = $(this).attr('id'); 
var articleIndex; 
$(this).parent().children('article').each(function (index) { 
    if ($(this).attr('id') == articleId) {articleIndex = index} 
}); 

上面的代碼工作,它只是不雅觀。一定有更好的方法!它是什麼?

+0

相關:http://stackoverflow.com/questions/2342376/how-to-find-position-number-of-a-specific-child-element-in-a-parent-element-using?rq = 1 – megawac

回答

1
$(this).parent().children() 

相當於

$(this).siblings() 

沒有?和

$(this).index() 

可能只是做這兩個工作。

http://jsfiddle.net/isherwood/VChu4/

+0

哇。我假設,因爲jquery對象通常是一個有活動元素$('.active')。index()總是返回0的數組。謝謝! – BGundlach

1

使用$ele.index

var $this = $(this); 
var articleId = $this.prop('id'); 
var $article = $this.find("#" + articleId); 
var index = $this.siblings('article').index($article); 

如果你正在努力尋找這樣的指標就用

var index $(this).parent().getChildren('articles').index(this); 
+0

TypeError:$(...)。parent(...)。getSiblings不是函數 – BGundlach

+0

@Bundlech我壞壞的複製粘貼 – megawac