$(function() {
$(".menu ul").on("click", "li", function(e) {
e.preventDefault();
alert($(this).closest("ul").prev().index());
alert($(this).index());
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="menu">
<li><a href="javascript:void(0);">C1</a>
<ul>
<li><a href="javascript:void(0);" class="documents">Assessments Not Started</a>
</li>
<li><a href="javascript:void(0);" class="messages">Assessments Started</a>
</li>
</ul>
</li>
<li><a href="javascript:void(0);">C2</a>
<ul>
<li><a href="javascript:void(0);" class="documents">Assessments Not Started</a>
</li>
<li><a href="javascript:void(0);" class="messages">Assessments Started</a>
</li>
</ul>
</li>
</ul>
&#13;
如何从上面获取PARENT LI索引以及点击的索引。
示例:
C2 > Assessments Started (should alert: 1, 1);
C1 > Assessments Not Started (should alert: 0, 0);
但它始终显示0作为最接近的索引。
答案 0 :(得分:2)
问题是因为您正在遍历DOM并获取a
元素,该元素是父ul
的兄弟,而不是li
父元素。试试这个:
$(".menu ul").on("click", "li", function(e) {
e.preventDefault();
console.log($(this).closest('ul').closest('li').index(), $(this).index());
});
答案 1 :(得分:1)
使用.parent()
选择器选择它。
$(function() {
$(".menu ul").on("click", "li", function(e) {
e.preventDefault();
alert($(this).parent().parent().index());
alert($(this).index());
});
});
答案 2 :(得分:1)
$(function() {
$(".menu ul").on("click", "li", function(e) {
e.preventDefault();
alert($(this).parents("li").index());
alert($(this).index());
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
<li><a href="javascript:void(0);">C1</a>
<ul>
<li><a href="javascript:void(0);" class="documents">Assessments Not Started</a></li>
<li><a href="javascript:void(0);" class="messages">Assessments Started</a></li>
</ul>
</li>
<li><a href="javascript:void(0);">C2</a>
<ul>
<li><a href="javascript:void(0);" class="documents">Assessments Not Started</a></li>
<li><a href="javascript:void(0);" class="messages">Assessments Started</a></li>
</ul>
</li>
</ul>
&#13;
答案 3 :(得分:1)
请试试。
$(this).closest("ul").parent();