jQuery Select 来自 HTML 的值 Table

jQuery Select Value from HTML Table

我是 jQuery 的新手。也许这是一个很简单的问题,但我不知道该怎么做。

我有这个table:

<table class="mytable">
<th>name</th>
<th>second</th>
<th>age</th>
  <tr>
    <td>Jill</td>
    <td>Smith</td>      
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>        
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>        
    <td>80</td>
  </tr>
</table>

我想在此 table 上方添加一个下拉列表,您可以在其中 select 关注 values/ages:50 或以下/51 - 80 / 80 及以上。

例如,如果“80 岁及以上是 selected”,则 table 中应仅显示 John Doe(80 岁)和 Eve Jackson(94 岁)。

将 table 详细信息存储在 json 对象中,例如
var table_data = [['Jill','Smith',50],['Eve','Jackson',94],['John','doe','80']]

然后使用以下代码为下拉列表创建更改事件


var table_data_html = '<table class="mytable"><th>name</th><th>second</th><th>age</th>'
for (var i = 0; i < table_data.length; i++) {
   if (your custom condition with table_data[i][2]  for example table_data[i][2]<50 ){
     table_data_html+='<tr id="black"><td>'+table_data[i][0]+'</td><td>'+table_data[i][1]+'</td><td>'+table_data[i][2]+'</td></tr>'
   }


};
table_data_html+='</table>'

然后您将此 table_data_html 值分配给任何 div,如下所示

$('#div_id').html(table_data_html);

你可以试试这个:

HTML

<select id="age">
    <option>Select</option>
    <option value="50">50 or below</option>
    <option value="80">51 - 80</option>
    <option value="100">80 and above</option>
</select>
<table class="mytable">
    <tr>
    <th>name</th>
    <th>second</th>
    <th>age</th>
    </tr>  
    <tr>
    <td>Jill</td>
    <td>Smith</td>      
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>        
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>        
    <td>80</td>
  </tr>
</table>

JS

$("#age").on("change", function(){
    $("tr").show();
    if($(this).val()=="50") {
        $("table tr").not(":first").each(function(){
            if($(this).find("td:last").html()==50) {
                $(this).show();
            }
            else {
                $(this).hide();
            }
        }); 
    }
    if($(this).val()=="80") {
        $("table tr").not(":first").each(function(){
            if($(this).find("td:last").html()>50 && $(this).find("td:last").html()<=80) {
                $(this).show();
            }
            else {
                $(this).hide();
            }
        }); 
    }
    if($(this).val()=="100") {
        $("table tr").not(":first").each(function(){
            if($(this).find("td:last").html()>80) {
                $(this).show();
            }
            else {
                $(this).hide();
            }
        }); 
    }
});

DEMO