如何获取表中当前元素之前出现的某些类的元素数?

时间:2015-08-31 05:35:58

标签: javascript jquery html css

我正在尝试使用类trsLot

对表格sLineitem编制索引

Lineitem属于Lot的层次结构。



    <table style="width:100%;" id="summarytable">
        <tr class="sLot">
            <td>Lot1</td>
        </tr>
        <tr class="sLineitem">
            <td>Lineitem1</td>
        </tr>
        <tr class="sLot">
            <td>Lot2</td>
        </tr>
    </table>
&#13;
&#13;
&#13;

我希望看起来像这样:

1   Lot1
    Lot1 desc
1.1 Lineitem1
2   Lot2
2.1 Lineitem1 under lot2

假设,使用table是唯一的选择。

1 个答案:

答案 0 :(得分:0)

我认为这对你有用

&#13;
&#13;
//Add the extra column to all rows
$('tr').prepend($('<td />', {
  class: 'srno'
}));

$('.sLot').each(function(i, el) {
  //get the index of the current sLot element
  var index = i + 1;
  //set the current sLot rows index text 
  $(el).find('.srno').text(index);
  //find all rows in between this and the next sLot that are .sLineitem and set their text
  $(el).nextUntil('.sLot').filter('.sLineitem').each(function(j, el2) {
    $(el2).find('.srno').text(index + '.' + (j + 1));
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%;" id="summarytable">
  <tr class="sLot">
    <td>Lot1</td>
  </tr>
  <tr class="sLineitem">
    <td>Lineitem1</td>
  </tr>
  <tr class="sLot">
    <td>Lot2</td>
  </tr>
</table>
&#13;
&#13;
&#13;

https://jsfiddle.net/4p0sw3fy/1/