【问题标题】:jQuery getting element index despite wrapper / parent element?尽管包装器/父元素,jQuery 获取元素索引?
【发布时间】:2012-05-23 18:41:12
【问题描述】:

我有相同类的 div,但每 3 个都包含在一个父 div 中。我无法按照我想要的方式获取索引。很抱歉,当我单击任何元素时,谁能帮我将索引设为 0 到 8 的数字?尽管有父元素。

这是我用于测试的完整代码。

<div class="more-content">
    <div class="post">post 1</div>
    <div class="post">post 2</div>
    <div class="post">post 3</div>
</div>
<div class="more-content">
    <div class="post">post 4</div>
    <div class="post">post 5</div>
    <div class="post">post 6</div>
</div>
<div class="more-content">
    <div class="post">post 7</div>
    <div class="post">post 8</div>
    <div class="post">post 9</div>
</div>

<script type="text/javascript">
$(function() {

    // navigate posts with next/prev buttons
    $(".post").click(function(){
        alert($(this).index());
    });

});
</script>

如果我单击我会得到索引 0、1、2 ..我认为是因为每 3 个项目都包含在父项中?我是 jquery 的新手,任何帮助表示赞赏。我需要的是获取具有相同类别的帖子的索引.. 说帖子 6 = 索引 5.. 等等

更新 如果单击的元素是帖子 div 中的子锚点而不是直接帖子 div,我如何获得相同的结果?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    尝试index 方法,将this 作为参数:

    $(".post").click(function() {
        alert($(".post").index(this));
    });​
    

    演示: http://jsfiddle.net/Nryf3/

    【讨论】:

    • 可以添加+ 1来反映帖子编号而不是div中的索引
    • @HunterMcMillen 那么它就不是索引了。
    • 我的错误,我认为那是 OP 正在寻找的内容
    • 如果我使用的是链接而不是实际的 .post,如果点击是 .post 的子锚点而不是锚点,我如何获得 index(this) 的替代品.post 本身.. ?
    • 我的意思是。如果单击是在 .post 本身上,则此解决方案有效,如果单击是在 .post 中的子元素锚点上怎么办?如何使 index(this) 起作用?..
    【解决方案2】:
    var posts = $('.post').click(function(){
        alert(posts.index(this));
    });
    

    演示: http://jsfiddle.net/paZ2e/

    【讨论】:

      【解决方案3】:

      您可以遍历所有标记为 post 的元素并增加一个计数器,直到找到您要查找的对象,如下所示:

      $(".post").click(function() {
          var counter = 0;
          var that = this;
      
          $(".post").each(function() {
              if(that == this) break;
              counter++;
          }
      
          // counter now equals the index of the post element out of all posts on the page
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-27
        • 1970-01-01
        • 2011-12-07
        • 2014-11-05
        • 2012-04-10
        • 2012-04-12
        • 1970-01-01
        • 2014-12-15
        相关资源
        最近更新 更多