jquery - 如何使用类获取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;我应该怎么办 ?
解决方案
使用函数时,您不需要在参数中再次指定元素.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>
推荐阅读
- java - MouseListener seems to doesn't work on EmbeddedMediaPlayerComponent
- haskell - `StateT a STM b` 中的 Haskell IO 操作
- c# - 为什么即使我将 Expires 设置为 null,JWT 仍包含 EXP 声明?
- gitlab-ci - 我需要 gitlab runner 来为我在 gitlab 中的项目执行 CICD 吗?
- apache - 如何将 https://www.subdomain.domain.com 转发到 https://subdomain.domain.com
- selenium - Intern3.1.1 /Chrome 76 /selenium3..5.3- Command#switchToFrame 失败
- java - ButtonSprite OnClickListener 不起作用
- python - 如何检查python函数是否返回true或false
- javascript - Javascript:如何从多个原型调用函数?
- python - 将列表理解转换为循环