递增类,需要从头开始停止和启动

时间:2014-01-03 19:00:15

标签: javascript jquery

我有一个脚本,它为一个表提供了一个递增的类,但是,我有一个多个表,这些表需要应用相同的类。在一个表的末尾,它只是继续增加类。

当前:class =:1,2,3,4,5,6 [表格末尾] 7,8,9,10,11,12

我在寻找:class =:1,2,3,4,5,6 [表格末尾] 1,2,3,4,5,6

这是我的剧本:

<script>
    var j = 1;
$("table.mobile_table tr").each(function(){
   $(this).attr("class", j++); // Give rows incrementing class
});
</script>

2 个答案:

答案 0 :(得分:3)

<script>

$("table.mobile_table").each(function(){
   var j = 1;
   var currentTable = $(this);
   currentTable.find("tr").each(function(){
      $(this).attr("class", j++);
   });

});
</script>

答案 1 :(得分:2)

您需要为每个表重置j变量。你也可以这样做。

$("table.mobile_table tr").addClass(function(){
    return ($(this).closest('.mobile_table tr').index(this) + 1);
});

或者

$("table.mobile_table").each(function(){
   $(this).find('tr').addClass(function(i){
          return i+1;
   });
});
相关问题