【问题标题】:jquery get index of parentjquery获取父级索引
【发布时间】:2021-11-18 09:55:44
【问题描述】:

我在使用 Jquery 时遇到问题,找不到解决方案。

这是我的代码结构:

<div class="parent">
    <div class="child"> Click here</div>
</div>
<div class="parent">
    <div class="child"> Click here</div>
    <div class="child"> Click here</div>
</div>
<div class="parent">
    <div class="child"> Click here</div>
</div>

我想在单击任何子 div 时检索父 div 的索引。就像我点击第二个父 div 的子元素一样,我想得到一个 2。我找不到正确的 Jquery 行来执行此操作。

有人做过吗?

谢谢

【问题讨论】:

  • api.jquery.com/index ?它是从零开始的,所以你的第二个需要 +1
  • 可悲的是 jQuery(this).parent().index() 如果我点击第一个父母的孩子或第二个父母的孩子,总是检索相同的值。
  • 是的,我知道 +1 thx :)
  • 你能添加你现有的jquery吗?点击事件——你在使用() =&gt;吗?

标签: jquery indexing parent


【解决方案1】:

index()

如果没有参数传递给 .index() 方法,则返回值是一个整数,指示 jQuery 对象中的第一个元素相对于其兄弟元素的位置。

$(".child").click(function() {
  console.log($(this).closest(".parent").index() + 1);
});
.parent {
  border-bottom: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="parent">
    <div class="child"> Click here</div>
  </div>
  <div class="parent">
    <div class="child"> Click here</div>
    <div class="child"> Click here</div>
  </div>
  <div class="parent">
    <div class="child"> Click here</div>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多