简体   繁体   中英

how to get an index of an element deep inside the DOM

is there anyway I could know which link I clicked relatively to the div.grid in the following html?

<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>

I tried:

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

but in the first two cases it returns -1 on every link and on the third 2 (always on every link).

It should be

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

For demo:

 $('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>

If you get a collection of all the links, you can then get the index based on that collection:

 // 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>

You need to retrieve the index of the parent figure element. Not the index of the anchor tag.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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