简体   繁体   English

筛选动态创建的表行(jQuery)

[英]Filtering table rows that are dynamically created (Jquery)

I have to filter a table (containing name, surname, phone and address of users) based on the input provided inside a search bar. 我必须根据搜索栏中提供的输入来过滤一个表(包含用户的姓名,姓氏,电话和地址)。

The content of the table is added dynamically with jquery using a form. 该表的内容是通过jquery使用表单动态添加的。

The following code is what I have been able to do so far regarding filtering the table rows (It works just with table rows encoded inside the html, not with table rows dynamically added with jquery). 到目前为止,以下代码是我能够进行的有关过滤表行的操作(它仅适用于html内编码的表行,不适用于通过jquery动态添加的表行)。

I'm aware of the possibility of adding a delegated event handler on the .on() function, but I haven't been able to write the code that would do the job. 我知道在.on()函数上添加委派事件处理程序的可能性,但是我无法编写完成此任务的代码。

 //Code that filters table rows according to user's search bar content $("#search").on("keyup", function() { var value = $(this).val().toLowerCase(); $("#myTable tr").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) }); }); 
 <input type="text" id="search" placeholder="Search for names.."> <!-- This is my search bar --> 

Thanks a lot, Luca P. 非常感谢Luca P.

You can use this function 您可以使用此功能

    $("#search").on("keyup", function() {
    var input, filter, table, tr, td, i;
    input = $("#search");
    filter = input.val().toUpperCase();
    table = $("#table");
    tr = table.find("tr");

    tr.each(function () {
        var linha = $(this);
        $(this).find('td').each(function () {
            td = $(this);
            if (td.html().toUpperCase().indexOf(filter) > -1) {
                linha.show();
                return false;
            } else {
                linha.hide();
            }
        })
})
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM