jQuery:保持.index()返回每个父项索引

时间:2011-12-12 17:49:54

标签: jquery indexing parents

在下面的代码中,我试图找回单击元素的索引,如果是,则返回其父索引。问题是它还试图返回其父级索引......

例如:如果我点击“1”,警报将返回0,0这是好的。 如果我点击A2,警报将返回0,1(这也是好的),然后返回1,0(父“坐标”)! 我想保留它以返回父数组...

<ul>
    <li>1</li>
    <li>2
    <ul>
        <li>A2</li>
        <li>B2</li>
        <li>C2</li>
    </ul>
    </li>
    <li>3</li>
    <li>4</li>
    <li><5</li>
</ul>


$('#control ul li').click(function(e) { 
    e.preventDefault();

    var child = $(this).index(); // Get actual li element index
    var parent = $(this).parents('li').index(); // Get the later parent index
    if(parent === -1) { parent = 0; } // If it doesn't have a parent set -1 to 0
    var current = $.makeArray([child,parent]); // Make an array of the coordinate 

    alert(current);


    switcher(current);
});

1 个答案:

答案 0 :(得分:1)

您应该停止事件传播。试试这个

$('#control ul li').click(function(e) { 
   e.stopPropagation();

   var child = $(this).index(); // Get actual li element index
   var parent = $(this).parents('li').index(); // Get the later parent index
   if(parent === -1) { parent = 0; } // If it doesn't have a parent set -1 to 0
   var current = $.makeArray([child,parent]); // Make an array of the coordinate 

   alert(current);


   switcher(current);
});