2

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

例如:如果我点击“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);
});
4

1 回答 1

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);
});
于 2011-12-12T17:53:07.927 回答