2017-01-12 114 views
0

我正在處理此表,如果該列沒有數據,需要過濾行。我可以過濾掉整個表格,但是我無法過濾出特定列的行。任何幫助將非常感激。過濾jQuery數據錶行

https://jsfiddle.net/mleitao/twg0qqq2/

$(document).ready(function() { 
$('#camera').click(function() { 
    $("#table-ActiveRooms tr td").each(function() { 
     var cell = $(this) 
     if (cell.children().length == 0) { 
      $(this).parent().hide(); 
     } 
    }); 
}); 

$('#btnReset').click(function() { 
    $("#table-ActiveRooms tr").each(function() { 
     $(this).show(); 
    }); 
}); 

}); 

回答

1

您需要專門的td選擇與您選擇的過濾器爲它工作。在您的代碼中,當線路中的任何td爲空時,您將隱藏tr

您可以添加一個類來識別這些TD,像IH此琴:https://jsfiddle.net/ttk2dy3f/2/

編輯:對不起,我忘了保存小提琴,現在

+0

感謝您的簡單修復!非常感謝 – perirose

+1

這可以在不使用類,'.each'循環,if語句等的情況下完成。爲了提高效率和可讀性,我強烈建議以我的答案爲高峯。否則,如果這是您選擇的解決方案,請確保接受它。 – Santi

+0

完全正確的Santi,考慮到問題的級別,我首先解釋hiw什麼是錯的,簡單地說,一步一步走。如果你想downvote做你喜歡的,不要在這裏代表;) – Kaddath

-1

做這將過濾器的基礎上下拉,你可以將它應用到你的代碼中。數據[1]是您要過濾的列。

var employeeName = ''; 

     $.fn.dataTable.ext.search.push(
     function (settings, data, dataIndex) { 
      if (data[1].indexOf(employeeName) > -1) { 
       return true; 
      } 
      else { 
       return false; 
      } 
     } 
    ); 



    $(document).ready(function() { 
     $('#employeeSelection').change(function (event) { 
         employeeName = $('#employeeSelection').val(); 

         table.draw(); 
        }); 

var table = $('#mainGrid').DataTable({ 
       paging: false, 
       ordering: true, 
       aaSorting: [], 
       scrollX: true, 
       searching: true, 
       dom: 'Bfrtip', 
       buttons: [ 
        'print' 
       ] 
      }); 

     }); 
2

你所得到的一些建議過於複雜。您不需要使用.each,也不需要if語句來檢查空值。

通過修改您的選擇器以使其更具體一些,您的代碼可以更清潔,更高效,而無需使用單個eachif

在這裏看到:https://jsfiddle.net/twg0qqq2/44/

$(document).ready(function() { 

    $tableRows = $("#table-ActiveRooms tr"); 

    $('#camera').click(function() { 
     $tableRows.has("td:nth-child(2):empty").hide(); 
    }); 

    $('#monitor').click(function() { 
     $tableRows.has("td:nth-child(3):empty").hide(); 
    }); 

    $('#phone').click(function() { 
     $tableRows.has("td:nth-child(4):empty").hide(); 
    }); 

    $('#btnReset').click(function() { 
     $tableRows.show(); 
    }); 
}); 

nth-child(2)的2代表列2.你可以假設,我們簡單地改變這個號碼匹配monitorphone

+0

我喜歡你的答案,我認爲這是一個更清潔,更容易閱讀。謝謝我感謝你的幫助。 – perirose