繁体   English   中英

查找元素相对于特定父级的索引

[英]finding the index of an element in relation to a specific parent

在这里查看示例-http: //jsfiddle.net/uqYeQ/3/

第一行的行为符合预期,返回其父级中div的索引。

我希望第二行的行为相同,我希望它返回0到4之间,具体取决于所单击的div。 我想知道与其父列表项相关的div索引。

我根本无法更改html。

旋转一下( 小提琴

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

这对我有用小提琴

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

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

但是反精神主义更性感。

以下是一种方法

$('.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM