我一直在尝试使用 jQuery(在 CoffeeScript 中)在表上实现用户可配置的过滤器。
我已使用 CSS 类对表格中的每一行进行了注释,该 CSS 类标识了其类别和品牌:
<table id="items_list">
<tr>
<th>Foo</th>
... <!-- 6 header columns -->
</tr>
<tr class="category-12 brand-37">
<td>...</td>
</tr>
<tr class="category-17 brand-4">
<td>...</td>
</tr>
我有<select>
下拉列表列出了所有类别,因此我尝试 Hook 它的 onChange 事件,以仅筛选出表中与该类别 ID 匹配的行。这是我到目前为止所得到的——每次我更改类别时它都会执行,但 selected_records 始终为空。
jQuery ->
items = $("#items-list").html() # works - though it has a <tbody> around it
$('#category_id').change -> # gets the onChange for the category dropdown
category_id = $('#category_id :selected').val() # this works, I get the id
# this next line always returns null
selected_records = $(items).filter("tr[class=category-#{category_id}]").html()
$('#items_list').html(selected_records)
倒数第二行肯定是错误的,但我不明白为什么。有什么想法吗?
最佳答案
您不必获取 html
并对其进行操作。您基本上可以只显示/隐藏 table
内的 tr
元素。此外,您还可以使用 this.val()
来获取 change
事件处理程序中 select
元素的选定值。试试这个。
var items = $("#items-list tr")
$('#category_id').change(function(){
//First hide all the trs
//then filter trs based on category-id class and show them
items.hide().filter(".category-" + $(this).val()).show();
});
关于jquery - 如何使用 jQuery 过滤表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8952243/