【问题标题】:jQuery - getting table rows following a filter matchjQuery - 在过滤器匹配后获取表行
【发布时间】:2016-12-28 07:12:22
【问题描述】:

我有一个使用 jQuery 过滤的 HTML 表格,以便根据具有特定类的单元格的内容删除行。以下代码适用于此:

$(function(){
    $('#data td.a1').filter(function() {
        return $(this).text().match(/some value/) != null;
    }).parent().remove();
});

但是,我还需要删除每个匹配行后面的两行。我怎样才能做到这一点?我几乎是一个 jQuery 新手。

非常感谢。

【问题讨论】:

    标签: javascript jquery filter html-table rows


    【解决方案1】:

    听起来像你想要的next

    $(function(){
        var items = $('#data td.a1').filter(function() {
            return $(this).text().match(/some value/) != null;
        }).parent();
        var next = items.next();
        var next2 = next.next();
        items.remove();
        next.remove();
        next2.remove();
    });
    

    编辑:我误读了。你想要下一个。
    编辑 2:如果您的表的结构使得您匹配的值每隔 3 行出现一次,因为 3 行的组在逻辑上相关,您可以使用 nextUntil 来获取下一个 2:

    $(function(){
        var items = $('#data td.a1').filter(function() {
            return $(this).text().match(/some value/) != null;
        }).parent();
        items.nextUntil('.3rdRowInPattern').remove();
    });
    

    另外,如果 3 行的组在逻辑上相关,您可以将每组 3 放入自己的 <tbody>(这是允许的)并删除 tbody。

    【讨论】:

    • 第 2 行和第 3 行包含基本上是垃圾输出的内容 - 这是由遗留系统产生的,否则我会从源头更改结构。您的第一个建议很完美,谢谢!
    【解决方案2】:

    我不得不猜测你的 HTML 结构。我在这里创建了一个小提琴。 http://jsfiddle.net/jaC72/2/

    <table id="data">
        <tr>
            <td class="a1">hello</td>
            <td class="a1">REMOVE</td>
            <td class="a1">hello</td>
        </tr>
        <tr>
            <td class="a1">hello</td>
            <td class="a1">hello</td>
            <td class="a1">hello</td>
        </tr>
        <tr>
            <td class="a1">hello</td>
            <td class="a1">hello</td>
            <td class="a1">hello</td>
        </tr>
    </table>
    

    脚本是这样的

    var removeExpression="REMOVE";
    
    $(function () {    
        $('table#data tr').filter(function(){
            var contains=false;
    
            $(this).find('td').each(function(index,value){            
                contains=contains||$(value).text().match(removeExpression);
            });
    
            return contains;
        })    
        .addClass('markedForRemoval')
        .next().addClass('markedForRemoval')
        .next().addClass('markedForRemoval'); 
    
         $('table#data').find('.markedForRemoval').remove();
    });
    

    【讨论】:

    • 它适用于fadeOut(),但不适用于remove()。这是因为 remove 会立即将元素从文档中取出,所以没有下一个。
    猜你喜欢
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 2012-04-28
    • 1970-01-01
    相关资源
    最近更新 更多