Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

javascript - To find Next element data-id of list in JQuery

How to get the data-id of next list element from the current active list element on button click?

 <div class="nbrs">
    <ul>
      <li id="item1" data-id="1" class="active">Coffee (first li)</li>
      <li id="item2" data-id="2">Tea (second li)</li>
      <li id="item3" data-id="3">Green Tea (third li)</li>
    </ul>
    </div>

   <button id="btnNext" type="button">Next</button> 

The next element data-id need to be shown till the last (third) li.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can find next li with .next('li') and find its attribute data-id value with .attr('data-id'). Remove active class from currently active li with $('li.active').removeClass('active'); & add active class in next li with next.addClass('active');.

Try like below.

$('#btnNext').click(function() {
  // find next li from currently active li
  let next = $('li.active').next('li');
  if (next.length > 0) {
    // remove active class from currently active li
    $('li.active').removeClass('active');
    // add active class in next li
    next.addClass('active');
    // get data id from next li
    let dataId = next.attr('data-id');
    alert(dataId);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div class="nbrs">
  <ul>
    <li id="item1" data-id="1" class="active">Coffee (first li)</li>
    <li id="item2" data-id="2">Tea (second li)</li>
    <li id="item3" data-id="3">Green Tea (third li)</li>
  </ul>
</div>

<button id="btnNext" type="button">Next</button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...