查找与特定父级相关的元素索引

时间:2012-04-27 13:03:26

标签: javascript jquery

查看此处的示例 - http://jsfiddle.net/uqYeQ/3/

第一行的行为与预期一致,返回div的父级内的div的索引。

我希望第二行以相同的方式运行,我希望它在0到4之间返回,具体取决于单击了哪个div。我想知道相对于它的父列表项单击的div的索引。

我根本无法更改html。

3 个答案:

答案 0 :(得分:5)

给它一个旋转(fiddle

$("li > .myclass, li > .container").click(function(e){
    $("#result").html($(this).index());            
});

答案 1 :(得分:1)

这对我有用(fiddle

$('.myclass').click(function(){
   var theIndex = $(this).index();
   $('#result').html(theIndex);
})

$('.container').click(function(){
    var theIndex = $(this).index();
    $('#result').html(theIndex);
})

但是反社会更性感。

答案 2 :(得分:0)

以下是一种方法

$('.myclass').click(function() {
    var liElem = $(this).parents('li')[0]; // get li element who is a parent of the clicked element
    var elems = $(this).parents();
    elems.push($(this)); //array contains all parents of the clicked element and the clicked element
    $(elems).each(function(key, elem) {
        if ($(elem).parent()[0] == $(liElem)[0]) {
            $('#result').html($(elem).index());
        }
    });
})

jsFiddle