如何按特定参数显示表格行?

时间:2017-02-17 02:00:10

标签: php jquery html html5

我有一排桌子。

<tr class='tr_h' title='fruits'><td>This is fruits row</td></tr>
<tr class='tr_d' title='fruits'><td>Apple</td></tr>
<tr class='tr_d' title='fruits'><td>Chicken</td></tr>
<tr class='tr_d' title='fruits'><td>Beef</td></tr>
<tr class='tr_d' title='fruits'><td>Pea</td></tr>
<tr class='tr_h' title='meats'><td>This is meat row</td></tr>
<tr class='tr_d' title='meats'><td>Apple</td></tr>
<tr class='tr_d' title='meats'><td>Chicken</td></tr>
<tr class='tr_d' title='meats'><td>Beef</td></tr>
<tr class='tr_d' title='meats'><td>Pea</td></tr>
<tr class='tr_h' title='nuts'><td>This is nuts row</td></tr>
<tr class='tr_d' title='nuts'><td>Apple</td></tr>
<tr class='tr_d' title='nuts'><td>Chicken</td></tr>
<tr class='tr_d' title='nuts'><td>Beef</td></tr>
<tr class='tr_d' title='nuts'><td>Pea</td></tr>

我尝试按标题值显示表格行。我想要的表:

<tr class='tr_h' title='fruits'><td>This is fruits row</td></tr>
<tr class='tr_d' title='fruits'><td>Apple</td></tr> 
<tr class='tr_h' title='meats'><td>This is meat row</td></tr>    
<tr class='tr_d' title='meats'><td>Chicken</td></tr>
<tr class='tr_d' title='meats'><td>Beef</td></tr>    
<tr class='tr_h' title='nuts'><td>This is nuts row</td></tr>
<tr class='tr_d' title='nuts'><td>Pea</td></tr>

这些行由php代码生成并完全像那样显示。我已经尝试使用jQuery对表进行排序。但是,它没有按预期工作:

$('.tr_h').each(function(){
     var id_m = $(this).attr('title')

     $('.tr_d').each(function(){ 
          var id_d = $(this).attr('title');

          if(id_d != id_m){ $(this).css('display','none'); }
          else{ $(this).css('display','block')};
     });
});

PS:请不要评论我使用title属性:D。谢谢。

2 个答案:

答案 0 :(得分:0)

我自己无法解释......

但是这个jQuery代码应该工作......不知怎的......就像你想要的那样:

var pos=0;
$('.tr_h').each(function(i) {
    var yea = $(this).nextUntil('.tr_h');
    yea.not(yea.slice(pos,pos+1+(i==1))).hide();
    pos+=(i==1);
    pos++;
});

答案 1 :(得分:0)

我发现另一个jQuery:

$('.tr_d').each(function(){
   var id_d = $(this).attr('title')
   var id_m = $(this).closest('tbody').find('.tr_h').attr('title');

   if(id_d != id_m){$(this).css('display','none'); }
});