简体   繁体   中英

Get 'this' selector index

I have following code, i need detect my clicked element index:

$('#id1, #id2, #id3').click(function(){ console.log( magicIndex(); ) });

When I click <div id="id1">click</div> div, I need to get 0 as output, because this selector item index is 0.

When I click <div id="id2">click</div> , I must get 1 as output.

Hope this helps. Here I am getting index from div 'id'.

 function magicIndex(node){ return node.attr('id').replace('id','')-1; } $('#id1, #id2, #id3').click(function(){ console.log( magicIndex($(this)) ); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="id1">Hi</div> <div id="id2">Hello</div> <div id="id3">Bye</div> 

Instead of 'id' if you add one more attr index in div that will be more specific and meaningful as we can not depend on 'id'. something like this

 function magicIndex(node){ return node.attr('index'); } $('#id1, #id2, #id3').click(function(){ console.log( magicIndex($(this)) ); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="id1" index='0'>Hi</div> <div id="id2" index='1'>Hello</div> <div id="id3" index='2'>Bye</div> 

You just need to use the jQuery function index(). This will return the position of the element, if the HTML structure is correct. I just created a jsfiddle for you:

https://jsfiddle.net/zLs4fo0f/6/

HTML:

<div>
  <div id="id1">
    aaaaaa
  </div>
  <div id="id3">
    bbbbbb
  </div>
  <div id="id2">
    cccccc
  </div>
</div>

<div id="result" style="color: red;">

</div>

jQuery:

$('#id1, #id2, #id3').on('click', function() {
    $('#result').text('Index: ' + $(this).index());
});

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