gpt4 book ai didi

jquery - 如何使用 class 获取 div 内元素的索引

转载 作者:行者123 更新时间:2023-12-01 04:35:39 25 4
gpt4 key购买 nike

我想获取所需 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')中parent的索引。例如,对于第二个 grandParent 的第一个父级,返回 3 而不是 0;对于最后一个父级,返回 4 而不是 1;我该怎么办?

最佳答案

使用 .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>

关于jquery - 如何使用 class 获取 div 内元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57450604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com