我有一个表,其td值对应于select下拉列表的值。因此,当选择下拉列表时,我希望表格根据所选值过滤其表格行。例如,如果选择了一个, 该表将进行过滤,只显示两个表行,其td值为1.目前,代码由于某种原因不起作用。
$(document).ready(function($) {
$('#select').change(function() {
var selection = $(this).val();
var dataset = $('#select').find('tr');
dataset.show();
dataset.filter(function(index, item) {
return $(item).find('td:first-child').text().split(',').indexOf(selection) === -1;
}).hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id='select'>
<option value="1"> One </option>
<option value="2"> Two </option>
<option value="3"> Three </option>
<option value="4"> Four </option>
</select>
<table border="2">
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
<tr><td>1</td></tr>
</table>
答案 0 :(得分:5)
只需使用表而不是选择
var dataset = $('table').find('tr');
$(document).ready(function($) {
$('#select').change(function() {
var selection = $(this).val();
var dataset = $('table').find('tr');
dataset.show();
dataset.filter(function(index, item) {
return $(item).find('td:first-child').text().split(',').indexOf(selection) === -1;
}).hide();
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id='select'>
<option value="1"> One </option>
<option value="2"> Two </option>
<option value="3"> Three </option>
<option value="4"> Four </option>
</select>
<table border="2">
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
<tr><td>1</td></tr>
</table>
&#13;
答案 1 :(得分:5)
selectfilter($('table'),$('#select').val());
$('#select').change(function() {
var selection = $(this).val();
$('table').find('tr').show();
selectfilter($('table'),selection);
});
function selectfilter(table ,selection)
{
table.find('tr').filter(function(index, item) {
return $(item).find('td:first-child').text().split(',').indexOf(selection) === -1;
}).hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='select'>
<option value="1"> One </option>
<option value="2"> Two </option>
<option value="3"> Three </option>
<option value="4"> Four </option>
</select>
<table border="2">
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
<tr><td>1</td></tr>
</table>