使用html select来进行ajax刷新以过滤表

时间:2015-07-07 05:24:41

标签: javascript jquery html ajax

正如标题中所提到的,我想知道如何制作一个HTML选择框来制作ajax请求并使用它来过滤表。我搜索了很多,但无法找到一个好的解决方案。 我怎样才能让它过滤?

My source code on jsfiddle.net

<select>
    <option value="all">All</option>
    <option value="tim">Tim</option>
    <option value="cook">Cook</option>
</select>
<br>
<br>
<br>
<table border="1">
    <tr>
        <th>Name</th>
        <th>Year</th>
    </tr>
    <tr>
        <td>Tim</td>
        <td>2015</td>
    </tr>
    <tr>
        <td>Cook</td>
        <td>2015</td>
    </tr>
</table>

1 个答案:

答案 0 :(得分:0)

你的例子有点奇怪,因为你只是过滤到一行,但这是你如何使它工作。

首先,将<select><table>分别作为身份证明。我选择了一些通用的东西:

<select id='column-select'>
    <option value="all">All</option>
    <option value="tim">Tim</option>
    <option value="cook">Cook</option>
</select>
<br>
<br>
<br>
<table id='data' border="1">
    <tr>
        <th>Name</th>
        <th>Year</th>
    </tr>
    <tr>
        <td>Tim</td>
        <td>2015</td>
    </tr>
    <tr>
        <td>Cook</td>
        <td>2015</td>
    </tr>
</table>

现在,只需使用一些Jquery过滤掉列更改时您不想要的行

$(document).ready(function() { // Do nothing until document is ready
    $("#column-select").change(function() { // On <select> change... 
        var selection = $("#column-select").val();
        if (selection == "all")
        {
            $("#data tr").show(); // Show all rows
        } else
        {
            $("#data tr").each(function() { // For each row
                if ($(this).find("th").length == 0) // If this is not a heading row
                {
                    if ($(this).find("td").eq(0).text().toLowerCase() == selection)
                    {
                        // Show rows where the first column matches
                        $(this).show(); 
                    } else
                    }
                        // Hide rows where the first column does not match
                        $(this).hide();
                    }
                }
            });
        }
    });
});

Here is a jsfiddle来演示。