繁体   English   中英

如何获取 DOM 深处元素的索引

[英]how to get an index of an element deep inside the DOM

无论如何我可以知道我点击了相对于以下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,在第三个 2 上(始终在每个链接上)。

它应该是

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>

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM