使用html select对筛选表进行ajax刷新

Using html select to make ajax refresh to filter table

本文关键字:ajax 刷新 筛选 html select 使用      更新时间:2023-09-26

如标题所述,我想知道如何制作一个HTML选择框来发出ajax请求并使用它来过滤表。我搜索了很多,但没有找到一个好的解决方案。我怎么能让它过滤?

我在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>

您的示例有点奇怪,因为您只过滤到一行,但以下是您如何使其工作的方法。

首先,给<select><table>各一个id。我选择了一些通用的:

<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();
                    }
                }
            });
        }
    });
});
相关文章: