【问题标题】:Get parent's index() value of the child获取孩子的父母的 index() 值
【发布时间】:2013-04-10 04:27:11
【问题描述】:

我如何获取被点击的 child $(this) 元素的 parent 元素相对于 document 的索引值?

HTML

<html>
   <body>
      <header>
         <div class="gallery">
            <div class="controls">
               <button class="next"></button>
               <button class="previous"></button>
            </div>
         </div>
      </header>
      <section>
         <section>
            <article>
               <div class="gallery">
                  <div class="controls">
                     <button class="next"></button>
                     <button class="previous"></button>
                  </div>
               </div>
               <div class="gallery">
                  <div class="controls">
                     <button class="next"></button>
                     <button class="previous"></button>
                  </div>
               </div>
            </article>
         </section>
      </section>
   </body>
</html>

在此 HTML 中,可以在正文中您喜欢的任何位置声明画廊。所以我需要一个“智能”选择器来解决这个问题。

伪 JavaScript

$('.controls button').click(function() {
   var hope = $(this).parents('.gallery').index();
   alert(hope);
}

预期输出

场景
单击此文档第二个库的按钮:

1

【问题讨论】:

  • 为什么你的 HTML 没有结束标签?
  • 我认为它会更容易阅读。
  • 没有结束标签不容易阅读,你应该包括它们。
  • 你能做一个小提琴吗?
  • @MohammadAdil 我创建了一个working fiddle

标签: javascript jquery gallery selector indexing


【解决方案1】:

试试这个:

$('.gallery').index( $(this).parents('.gallery') );

.index() 正在查找所应用元素组中传递的元素的索引。

看看我的working jsFiddle example

来源

jQuery API - .index()

【讨论】:

    【解决方案2】:

    当您调用 index() 时,它会为您提供相对于您选择的元素集合的位置,在这种情况下,

    $(this).parents('.gallery')
    

    相反,您希望它相对于整个文档中的画廊,所以您需要:

    $('.gallery').index($(this).parents('.gallery'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 2015-08-30
      • 2013-06-04
      • 2018-01-29
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      相关资源
      最近更新 更多