如何检索索引

时间:2015-12-24 15:58:15

标签: jquery html



$(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;
&#13;
&#13;

如何从上面获取PARENT LI索引以及点击的索引。

示例:

C2 > Assessments Started (should alert: 1, 1);
C1 > Assessments Not Started (should alert: 0, 0);

但它始终显示0作为最接近的索引。

4 个答案:

答案 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());
});

Example fiddle

答案 1 :(得分:1)

使用.parent()选择器选择它。

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

答案 2 :(得分:1)

&#13;
&#13;
$(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;
&#13;
&#13;

答案 3 :(得分:1)

请试试。

$(this).closest("ul").parent();