无法获取元素的索引

时间:2018-12-17 09:34:03

标签: jquery

我想获取d-flex内部的#Equipmentsfield_wrapper的索引,但是我的代码不起作用。我知道那是错误的,但是我正在使用它

alert($('#Equipmentsfield_wrapper').children('div').index());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Equipmentsfield_wrapper">
  <div class="d-flex">
    <input type="text" class="form-control" name="equipments[]" value="" required/>
    <a href="javascript:void(0);" id="Equipmentsadd_button" class="fieldAddDeleteIcon" title="Add field"><i class="fa fa-plus"></i></a>
  </div>
  <div class="d-flex">
    <input type="text" class="form-control" name="equipments[]" value="" required/>
    <a href="javascript:void(0);" id="Equipmentsadd_button" class="fieldAddDeleteIcon" title="Add field"><i class="fa fa-plus"></i></a>
  </div>
</div>

1 个答案:

答案 0 :(得分:2)

您正在选择元素的集合。您可以循环打印索引。否则,您需要缩小收藏范围。

$('#Equipmentsfield_wrapper').children('div').each(function(){
  console.log($(this).index());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Equipmentsfield_wrapper">
  <div class="d-flex">
    <input type="text" class="form-control" name="equipments[]" value="" required/>
    <a href="javascript:void(0);" id="Equipmentsadd_button" class="fieldAddDeleteIcon" title="Add field"><i class="fa fa-plus"></i></a>
  </div>
  <div class="d-flex">
    <input type="text" class="form-control" name="equipments[]" value="" required/>
    <a href="javascript:void(0);" id="Equipmentsadd_button" class="fieldAddDeleteIcon" title="Add field"><i class="fa fa-plus"></i></a>
  </div>
</div>