添加类后获取元素索引

时间:2017-09-26 15:10:29

标签: javascript jquery html

添加特定类后,我对索引元素有问题。我需要索引不是从ul的第一个元素,而是从激活类的li开始。有可能吗?



function setdataindex() {
  $('.ul li').removeAttr('data-index');
  $('.ul li.activated').each(function() {
    var index = $(this).index();
    $(this).find('span').html(index);
  });
}
setdataindex();

$('form').on('change', function() {
  var nodeActive = $(this).find('input:checked').attr('id');
  $('.ul li').removeClass('activated');
  $('.ul li span').empty();
  $('.ul').find('[data-node="' + nodeActive + '"]').addClass('activated');
  setdataindex();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <p><input id="nd1" type="radio" name="node" value="node1">Node1 </p>
  <p><input id="nd2" type="radio" name="node" value="node2">Node2 </p>
</form>

<ul class="ul">
  <li data-node="nd1">Test <span></span></li>
  <li class="activated" data-node="nd2">Test <span></span></li>
  <li data-node="nd1">Test <span></span></li>
  <li data-node="nd1">Test <span></span></li>
  <li data-node="nd2">Test <span></span></li>
</ul>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

jQuery foreach方法将索引和值传递给回调:

function setdataindex() {
  $('.ul li').removeAttr('data-index');
  $('.ul li.activated').each(function(index) {
    $(this).find('span').html(index);
  });
}