如何使用Javascript在表格中选择多个项目

时间:2014-07-25 20:04:55

标签: javascript underscore.js tabular

使用这样的例子:

http://www.datatables.net/media/blog/bootstrap_2/

如何在表格中选择,而不是过滤Firefox和Mozilla。 我正在考虑使用select2.js来获取多个选定的项目。 然后用下划线处理表...如果有博客,解释 请列出。

1 个答案:

答案 0 :(得分:1)

我认为你要问的是:

  

我有一张桌子和一个多选框。我想在多选框中使用用户的选择来过滤表的行。如果未选择任何内容,则显示所有行。如果选择了两个选项,则仅显示与这两个选项对应的行。我怎样才能做到这一点?

这有效:

HTML

<select id="browserSelect" multiple style="width:300px">
    <option value="Firefox">Firefox</option>
    <option value="Mozilla">Mozilla</option>
    <option value="IE">IE</option>
    <option value="Netscape">Netscape</option>
    <option value="Opera">Opera</option>
</select>
<table>
    <tr>
        <td>Firefox</td>
        <td>details</td>
    </tr>
    <tr>
        <td>IE</td>
        <td>details</td>
    </tr>
    <tr>
        <td>Firefox</td>
        <td>more details</td>
    </tr>
    <tr>
        <td>Netscape</td>
        <td>details</td>
    </tr>
    <tr>
        <td>Mozilla</td>
        <td>details</td>
    </tr>
    <tr>
        <td>Opera</td>
        <td>details</td>
    </tr>
</table>

JS with jQuery and Select2:

$("#browserSelect").select2().change(function () {
    var selectedBrowsers = $('select').val();
    if (selectedBrowsers) {
    //If the user made a selection, hide every row of the table
        $('tr').hide();
        //Show only rows where the text in the first column
        //corresponds to one of the user's selections
        $('td:first-child').each(function (i, cell) {
            if (selectedBrowsers.indexOf($(cell).text()) > -1) {
                $(cell).parent().show();
            }
        });
    } else {
    //Show all rows when there is no selection
        $('tr').show();
    }
});

http://jsfiddle.net/Q526A/3/

我使用Select2使多选框更加用户友好,如你所知。