如何获取DOM内部元素的索引

时间:2017-10-11 17:31:56

标签: javascript jquery

无论如何我可以知道我在以下html中相对于div.grid点击了哪个链接?

<div class="grid">
  <figure class='grid-item'>
    <figcaption>
      <a>link</a>
    </figcaption>
  </figure>
  <figure class='grid-item'>
    <figcaption>
      <a>link</a>
    </figcaption>
  </figure>
  <figure class='grid-item'>
  .....
  </figure>
  ....
</div>

我试过了:

index = $('div.grid').index(this); // returns -1 on every link
index = $(this).parent().parent().parent().index(this); // returns -1
index = $(this).index(); // returns 2 on every link

但在前两种情况下,它在每个链接上返回-1,在第三个链接上返回-1(总是在每个链接上)。

3 个答案:

答案 0 :(得分:1)

应该是

var index = $(this).closest('.grid-item').index();

对于演示:

$('a').click(function(){
  var index = $(this).closest('.grid-item').index();
  alert(index);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="grid">
  <figure class='grid-item'>
    <figcaption>
      <a>link</a>
    </figcaption>
  </figure>
  <figure class='grid-item'>
    <figcaption>
      <a>link</a>
    </figcaption>
  </figure>
  <figure class='grid-item'>
    <figcaption>
      <a>link</a>
    </figcaption>
  </figure>
</div>

答案 1 :(得分:0)

如果您收到所有链接的集合,则可以根据该集合获取索引:

&#13;
&#13;
// Gather all the links in the section into an array:
var links = Array.prototype.slice.call(document.querySelectorAll(".grid a"));

// Set up an event handler for them:
links.forEach(function(link){
  link.addEventListener("click", function(){
    // Just get the current link's position in the array
    console.log(links.indexOf(this));
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid">
  <figure class='grid-item'>
    <figcaption>
      <a>link</a>
    </figcaption>
  </figure>
  <figure class='grid-item'>
    <figcaption>
      <a>link</a>
    </figcaption>
  </figure>
  <figure class='grid-item'>
    <figcaption>
      <a>link</a>
    </figcaption>
  </figure>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您需要检索父图元素的索引。不是锚标记的索引。

&#13;
&#13;
jQuery(document).on("click", ".grid a", function() {
  var figure = jQuery(this).parent().parent();
  
  //Retrieve the index of the figure.
  var index = jQuery(figure).index();
  
  alert(index);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid">
  <figure class='grid-item'>
    <figcaption>
      <a>link</a>
    </figcaption>
  </figure>
  <figure class='grid-item'>
    <figcaption>
      <a>link</a>
    </figcaption>
  </figure>
  <figure class='grid-item'>
  </figure>
</div>
&#13;
&#13;
&#13;