javascript - 获取 child 的 parent 的 index() 值

标签 javascript jquery gallery selector indexing

如何获取parent 元素与document 相关的索引值,点击child$(this ), 元素?

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);
}

预期输出

场景
点击这个文档second库的一个按钮:

1

最佳答案

试试这个:

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

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

看看我的working jsFiddle example .

来源

jQuery API - .index()

关于javascript - 获取 child 的 parent 的 index() 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16059534/

相关文章:

设置 header 时 AJAX 请求失败,但没有设置 header 时 AJAX 请求会成功

jquery - 将 JQuery 确认添加到任意元素的最佳不显眼的方法

java - Android Intent 打开图片库,但不打开图片。为什么?

javascript - 通过 javascript 在 Internet Explorer 中更改图像 src

javascript - jQuery tmpl if 对象值 == 当前迭代值

javascript - Rails Javascript haml 变量创建

javascript - 如何在 High Chart 中的一系列数据中显示不同的工具提示格式

javascript - 在 CodeIgniter 中加载 Controller 后运行 javascript

javascript - jQuery 附加一个 CSS 并运行一个函数?

css - WordPress:如何将画廊简码设计成砌体布局?