首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >查找sitewide元素的索引

问查找sitewide元素的索引
EN

Stack Overflow用户
提问于 2017-09-11 20:20:54
回答 1查看 19关注 0票数 0

我一直在尝试找出如何在站点范围内搜索某个类的元素索引。不一定是站点范围的,但我必须是祖先div的可用对象。

我的标记如下:

代码语言:javascript
复制
<div class="custom-woo-gallery">
    <div class="row">
        <div class="gallery-item"></div>
        <div class="gallery-item"></div>
        <div class="gallery-item"></div>
    </div>
    <div class="row">
        <div class="gallery-item"></div>
        <div class="gallery-item"></div>
        <div class="gallery-item"></div>
    </div>
    <div class="row">
        <div class="gallery-item"></div>
        <div class="gallery-item"></div>
        <div class="gallery-item"></div>
    </div>
    <div class="row">
        <div class="gallery-item"></div>
        <div class="gallery-item"></div>
        <div class="gallery-item"></div>
    </div>
    <div class="row">
        <div class="gallery-item"></div>
        <div class="gallery-item"></div>
        <div class="gallery-item"></div>
    </div>
</div>

基本上,单击一个.gallery-item元素,我需要找出在公共祖先.custom-woo-gallery中有多少个.gallery-item元素在它之前。

我有以下代码,它是功能性的。但我猜还有更简单的方法可以做到这一点。我只是在谷歌上找不到任何东西,除了index()和eq(),它们似乎只能在同一个父div中工作。

代码语言:javascript
复制
function getPrev(){
    var count = 0;
    $(clicked).parent().prevUntil().each(function(){
        count = count + $(this).children().length;
    })
    var self = $(clicked).prevUntil().length;
    return count + self;
}
EN

回答 1

Stack Overflow用户

发布于 2017-09-11 20:24:10

尝试此解决方案。如果你只有一个custom-woo-gallery,你可以通过获取当前点击的gallery-item的索引,并且你可以知道它前面有多少个.gallery-item元素。

实际上,被点击的div的index是他之前的.gallery-item的编号。

​

代码语言:javascript
复制
const galleryItems = $('.gallery-item');

$('.gallery-item').on('click', function(){
  console.log(galleryItems.index($(this)));
})
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-woo-gallery">
    <div class="row">
        <div class="gallery-item">1</div>
        <div class="gallery-item">2</div>
        <div class="gallery-item">3</div>
    </div>
    <div class="row">
        <div class="gallery-item">4</div>
        <div class="gallery-item">5</div>
        <div class="gallery-item">6</div>
    </div>
    <div class="row">
        <div class="gallery-item">7</div>
        <div class="gallery-item">8</div>
        <div class="gallery-item">9</div>
    </div>
    <div class="row">
        <div class="gallery-item">10</div>
        <div class="gallery-item">11</div>
        <div class="gallery-item">12</div>
    </div>
    <div class="row">
        <div class="gallery-item">13</div>
        <div class="gallery-item">14</div>
        <div class="gallery-item">15</div>
    </div>
</div>

​

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46155680

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档