如何正确链接jquery选择器?

时间:2013-12-05 09:41:38

标签: javascript jquery

我正在尝试使用jquery在我的表中实现快速搜索/过滤功能。本质上,我想隐藏所有没有我正在寻找的字符串的行,从搜索框中隐藏。

我有一个动态创建的表和一个用作列表过滤器的文本字段。

表:     

<table id="report-table" class="table">
<thead>
    <tr>
        <th class="">client</th>
        <th class="">coach</th>
        <th class="">groups</th>

    </tr>
</thead>

<tbody>
    <tr>
        <td class="name">John</td>
        <td class="coach">Peter </td>
        <td class="groups"> Skiers </td>
    </tr>
</tbody>

我有一个与搜索文本框的更改事件关联的函数。在这个函数中,我基本上想要选择所有不包含name或coach列中的文本字符串的tr,并为它们添加一个类。我尝试过很多东西,但是没有正确的语法,如何应该写吗?

hideSearch: function(e){

        console.log("hideSearch called");
        var searchValue = this.$el.find('.search-text').val();

        if(!searchValue ){
            console.log("hideSearch: empty search param");
            this.$el.find('tr').removeClass('hidden');
        }
        else{
            console.log("hideSearch: searched for: " + searchValue);
            //$('(#name, #groups):contains:not("'+searchValue+'")').parent().addClass('hidden');
            var selection =$('#name, #groups').('*:contains("'+searchValue+'")');

            console.log(selection);
            //console.log($('#name, #groups').('*:contains("'+searchValue+'")'));
            //$('(#name, #groups):contains("'+searchValue+'")').parent().addClass('hidden');
            //$('#name, #groups').('*:contains:not("'+searchValue+'")').parent().addClass('hidden');

        }

1 个答案:

答案 0 :(得分:2)

$('#name, #groups').('*:contains("'+searchValue+'")');基本上会尝试访问*:contains("foo")返回的对象的属性searchValue(假设"foo"$('#name, #groups'))。我相信我不必说jQuery对象没有这些奇怪名称的属性。

首先,您必须为所有单元格提供一个通用的而不是ID。然后,您应该选择所有行,并查看.name.coach是否包含搜索值。使用.filter获取两个都不匹配的那些:

$('#report-table > tbody > tr').filter(function() {
    return $(this).children('.name').text().indexOf(searchValue) === -1 &&
           $(this).children('.coach').text().indexOf(searchValue) === -1;
}).addClass('hidden');

如果true单元格和.name单元格都不包含搜索值,则过滤器回调会返回.coach。回调返回true的那些行保留在选择中,并且正在添加类hidden