Jquery滑块范围:将范围应用于表行的过滤器

时间:2015-01-08 13:38:24

标签: javascript jquery html filtering

对于我的实习,我必须为一个表格做一个过滤器,它必须只显示你给它的值之间的行。 现在我使用Jquery UI作为range slider,我有一个普通的html表。

我无法上班,我尝试过很多不同的事情。 这是我的代码:

$(function() {
            $( "#slider-range" ).slider({
              range: true,
              min: 0,
              max: 500,
              values: [ 75, 300 ],
              slide: function( event, ui ) {
                $( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );


            $( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) +
              " - $" + $( "#slider-range" ).slider( "values", 1 ) );

                $("#ADC_DAC").find("td:nth-child(0)").filter(function () {
                    return parseInt($(this).text()) < $( "#slider-range" ).slider( "values", 0 );
                }).parent().hide();

                $("#ADC_DAC").find("td:nth-child(0)").filter(function () {
                    return parseInt($(this).text()) > $( "#slider-range" ).slider( "values", 1 );
                }).parent().hide();
            }
         });
    });

滑块的ID为slider-range,表ID为ADC_DAC。 我的桌子是这样组成的:

<table id="ADC_DAC">
     <tr>
       <td>h1</td>
       <td>h2</td>
       <td>h3</td>
     </tr>
     <tr>
       <td>23</td>
       <td>test</td>
       <td>test2</td>
     </tr>
</table>

但是第一行有更多的行和0到500之间的值(需要过滤)

提前致谢:)

1 个答案:

答案 0 :(得分:6)

通过尝试更改slide: function() {}

中的表格属性,您走在正确的轨道上

但是,函数中的代码使用了find和其他不利的选择器。

最简单的方法是简单地选择表并按照这样的方式遍历每一行和每列:

var table = document.getElementById("theTable");

for (var i = 1, row; row = table.rows[i]; i++) {
   //iterate through rows (we SKIP the first row: counter starts at 1!)
   for (var j = 0, col; col = row.cells[j]; j++) {
       //iterate through columns: if first column not in range: HIDE, else SHOW

       if (j == 0) {             // if first column
           if ($(col).html() >= ui.values[ 0 ] && $(col).html() <= ui.values[ 1 ]) {
               // if in interval
               $(row).show();
           } else {
               $(row).hide();
           }
       }
   }  
}   

那应该做你想要的。此解决方案比您的解决方案容易得多,因为您无需处理.parent.children选择器。特别是对于像桌子这样的2D结构,for loops通常更容易掌握并保持良好的可读性。但是,它可能不是最短的代码。

这是有效的jsFiddle演示:

DEMO

enter image description here