簡體   English   中英

如何正確鏈接jquery選擇器?

[英]How do I chain jquery selectors properly?

我正在嘗試使用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');

        }

$('#name, #groups').('*:contains("'+searchValue+'")'); 基本上會嘗試訪問$('#name, #groups')返回的對象*: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');

如果.name單元格和.coach單元格都不包含搜索值,則過濾器回調返回true 回調返回true那些行保留在選擇中,並將hidden的類添加到它們中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM