简体   繁体   中英

jQuery - Identifying an object by its position (index) among siblings

What I'm trying to do is identify an element by its position within a div. I've tried the code below and it works, but I'm curious if there's a much more efficient way to do this.

HTML:

<div class="container">
  <button>One</button>
  <button>Two</button>
  <button>Three</button>
</div>

<div class="result"></div>

JavaScript:

$('.container button').on('click', function(e) {
  clickedBtn = e.target;
  btnNum = 0;

  $('.container button').each(function(i) {
    if ($(this)[0] === clickedBtn)
      btnNum = i+1;
  });

  $('.result').text('Clicked button #' + btnNum);
});

Since you are looking for index based in siblings you can call the .index() without any arguments.

 $('.container button').on('click', function(e) { $('.result').text('Clicked button #' + $(this).index()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="container"> <button>One</button> <button>Two</button> <button>Three</button> </div> <div class="result"></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