2012-01-21 87 views
3

我試圖在使用jQuery(在coffeescript)的表上實現用戶可配置的過濾器。如何使用jQuery過濾表格?

我已經註釋每一行中我的表標識其品類和品牌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>下拉列表列出所有類別的,所以我試圖鉤在它的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) 

倒數第二行必須是錯誤的,但我不明白爲什麼。有任何想法嗎?

回答

3

您不必獲取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(); 
    }); 
+0

美 - 謝謝。我剛剛意識到這一戰略拋棄了我的排,但我認爲我可以解決這個問題。謝謝你的幫助! –