Catch the next / previous specific attribute with jquery

My html

<table>
    <tr><td>w</td><td data-id='6' class='point'>6</td></tr>
    <tr><td>X</td><td data-id='8' class='point'>8</td></tr>
    <tr><td>Y</td><td data-id='7' class='point'>7</td></tr>
    <tr><td>Z</td><td data-id='10' class='point'>10</td></tr>
</table>

and js

$('.point').click(function(){
    alert($(".point").nextAll().attr('data-id:first'));
});

I want to get the value of the previous or next data-id, when I click any class points. How to solve it without using parent()and children(). My violin Demo screenshot Thank you.

+4
source share
2 answers

According to your requirement (do not use the "nearest" / parent / children / "find" ), you can use it .eq()together .index()to achieve what you need.

Give it a try

var point = $('.point');
point.click(function(){
    alert(point.eq(point.index(this) + 1).attr('data-id'));
});

Demo

+2
source

-, this . , .point nextAll(), . closest(), tr, tr, find() .point . :

$('.point').click(function(){
    alert($(this).closest('tr').next('tr').find('.point').data('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr><td>w</td><td data-id='6' class='point'>6</td></tr>
    <tr><td>X</td><td data-id='8' class='point'>8</td></tr>
    <tr><td>Y</td><td data-id='7' class='point'>7</td></tr>
    <tr><td>Z</td><td data-id='10' class='point'>10</td></tr>
</table>
Hide result
+1

Source: https://habr.com/ru/post/1583968/


All Articles