首页 > 解决方案 > 如何使用类获取div内元素的索引

问题描述

我想在所需的 div 中而不是在整个相同的类 div 中获取我的元素的索引。

$(function() {
  $('.child').change(function() {
    var control = $(this);
    var grandParentContainer = '.grandParent';
    var parentContainer = '.parent';
    var grandParentIndex = control.closest(grandParentContainer).index();
    var parentIndex = control.closest(parentContainer).index();
    console.log(grandParentIndex, parentIndex);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wholeContainer">
  <section class="grandParent">
    <div>
      <input type="text" name="grandTitle" placeholder="title">
    </div>
    <section class="parent">
      <div>
        <input type="text" name="parentTitle" placeholder="parent title">
        <select class="child">
          <option value="0">one</option>
          <option value="1">two</option>
          <option value="2">three</option>
        </select>
      </div>
    </section>
  </section>
  <section class="grandParent">
    <div>
      <input type="text" name="grandTitle" placeholder="title">
    </div>
    <section class="parent">
      <div>
        <input type="text" name="parentTitle" placeholder="parent title">
        <select class="child">
          <option value="0">one</option>
          <option value="1">two</option>
          <option value="2">three</option>
        </select>
      </div>
    </section>
  </section>
</div>

grandParentIndex正确的;但这parentIndex是错的。对于第一个 grandParent 是正确的,但对于 more ,它返回整个 div('.container') 中的父级索引。例如,对于第二个 grandParent 的第一个父级,返回 3 而不是 0;对于最后一个 parent ,返回 4 而不是 1;我应该怎么办 ?

标签: jquery

解决方案


使用函数时,您不需要在参数中再次指定元素.index(),此外,由于您已经存储$(this)control变量中,您不必稍后在代码中使用 jQuery 再次包装变量,试试这个:

$(function() {
  $('.child').click(function() {
    var control = $(this);
    var grandParentContainer = '.grandParent';
    var parentContainer = '.parent';
    var grandParentIndex = control.closest(grandParentContainer).index();
    var parentIndex = control.closest(parentContainer).index();
		console.log(grandParentIndex, parentIndex);

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="grandParent">
    <div class="parent">
      <button class="child">click</button>
    </div>
    <div class="parent">
      <button class="child">click</button>
    </div>
    <div class="parent">
      <button class="child">click</button>
    </div>
  </div>

  <div class="grandParent">
    <div class="parent">
      <button class="child">click</button>
    </div>
    <div class="parent">
      <button class="child">click</button>
    </div>
  </div>
</div>


推荐阅读