根据选择值过滤表行
我需要根据选择值过滤表行。 当选择的值为“”(空)时,必须隐藏表。 如果select值为1,则表必须可见,并且必须仅显示第一个表列保持值为1的行。
问题是这个id列包含多个id,如1,2。 由于我的JQuery技能不是最好的,我需要你们帮我完成我的代码
我的选择器
Please Select A B C
我的桌子
ids name address 1,2 Jhon Doe 3 Mike Poet 2,3 Ace Ventura
我的剧本
$(document).ready(function($) { $('table').hide(); $('#mySelector').change( function(){ $('table').show(); var selection = $(this).val(); var dataset = $('#myTable').find('tr'); $.each(dataset, function(index, item) { //help }); }); });
这里有工作人员
如果您需要任何其他信息,请告诉我,我会提供。 先感谢您。
您可以根据包含id s的td
的内容过滤行:
-
你的数据集必须是
$('#myTable tbody').find('tr')
所以它不会显示/隐藏thead
-
首先使用
dataset.show()
显示所有表格 -
现在过滤掉你不需要显示的
tr
:dataset.filter(function(index, item) { return $(item).find('td:first-child').text().split(',').indexOf(selection) === -1; }).hide();
见下面的演示:
$(document).ready(function($) { $('table').hide(); $('#mySelector').change(function() { $('table').show(); var selection = $(this).val(); var dataset = $('#myTable tbody').find('tr'); // show all rows first dataset.show(); // filter the rows that should be hidden dataset.filter(function(index, item) { return $(item).find('td:first-child').text().split(',').indexOf(selection) === -1; }).hide(); }); });
/* Styles go here */ table { border-collapse: collapse; width: 100%; } th, td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; } .styled-select.slate { height: 34px; width: 240px; }
ids name address 1,2 Jhon Doe 3 Mike Poet 2,3 Ace Ventura
尝试使用以下代码
$("#mySelector").on("change", function(){ var a = $(this).find("option:selected").html(); $("table tr td:first-child").each( function(){ if($(this).html() != a){ $(this).parent().hide(); } else{ $(this).parent().show(); } }); });
这是一个可以在这里测试的解决方案
$(function() { $('table').hide(); $('#mySelector').change( function(){ $('table').show(); var selection = $(this).val(); var dataset = $('#myTable').find('tr'); dataset.each(function(index) { item = $(this); item.hide(); var firstTd = item.find('td:first-child'); var text = firstTd.text(); var ids = text.split(','); for (var i = 0; i < ids.length; i++) { if (ids[i] == selection) { item.show(); } } }); }); });
使用的简短解决方案:contains()
选择器:
$(document).ready(function($) { $('table').hide(); $('#mySelector').change( function(){ var selection = $(this).val(); $('table')[selection? 'show' : 'hide'](); if (selection) { // iterate only if `selection` is not empty $.each($('#myTable tbody tr'), function(index, item) { $(item)[$(item).is(':contains('+ selection +')')? 'show' : 'hide'](); }); } }); });
测试链接: https : //plnkr.co/edit/zNQNFVBIPSyPjEyU7I1J?p = preview