在td上使用data-id参数过滤表

时间:2019-04-08 07:48:38

标签: jquery html-table

我试图用jquery创建一个过滤器表,这里的问题是我想对data-id的{​​{1}}值进行过滤。

因此,当我选择值为Yes = 1的选项时,它将转到具有参数<td>的过滤器字段<th>Option A</th>

示例HTML

data-id="1"

jquery

<select id="choice" class="form-control select2" >
    <option value="all">choice answer</option>
    <option value="1">Yes</option>
    <option value="2">No</option>
</select>

<table id="dt-answer"  width="100%" cellspacing="2">            
<thead>
    <tr class="headings">
        <th>No</th>
        <th>Question</th>
        <th>Answer</th>
        <th>Option A</th>
        <th>Option B</th>
    </tr>
</thead>                                      
<tbody>
    <tr>
        <td>1</td>
        <td>Question A</td>
        <td data-id="1">Yes</td>
        <td>Yes</td>
    </tr>
    <tr>
        <td>2</td>
        <td>Question B</td>
        <td data-id="2">No</td>
        <td>Yes</td>
    </tr>
    <tr>
        <td>3</td>
        <td>Question C</td>
        <td data-id="2">No</td>
        <td>No</td>
    </tr>
    <tr>
        <td>4</td>
        <td>Question C</td>
        <td data-id="1">Yes</td>
        <td>No</td>
    </tr>
    <tr>
        <td>4</td>
        <td>Question D</td>
        <td data-id="2">No</td>
        <td>No</td>
    </tr>
</tbody>
</table>    

1 个答案:

答案 0 :(得分:1)

保留.each(使用.fitler的地方)-将您的jquery更改为:

$('#choice').change(function() {
    var value = $(this).val().toLowerCase();
    $("#dt-answer tr").each(function() {
        $(this).toggle($(this).find(">td[data-id]").data("id") == value > -1)
    });
})  

.toggle内:

.find寻找匹配的后代(this,即tr
">td[data-id]"的{​​{1}}的直接后代,具有数据ID
td获取ID并与.data("id")

进行比较

有多种选择

value

例如在第三列中使用.find(">td[data-id]") .children()


在这种情况下,不需要td:eq(2)(/ .each),并且在循环中更改许多DOM元素可能会导致应用程序显示缓慢。您可以使用:

.filter