【问题标题】:Filtering Ajax loaded table过滤 Ajax 加载的表
【发布时间】:2016-12-27 06:12:31
【问题描述】:

我正在尝试使用 Javascript 过滤表格。我使用的代码如下:

var $rows = $('tr').not('#tr');
$('#search').keyup(function() {

    var val = '^(?=.*\\b' + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') + ').*$',
        reg = RegExp(val, 'i'),
        text;

    $rows.show().filter(function() {
        text = $(this).text().replace(/\s+/g, ' ');
        return !reg.test(text);
    }).hide();
});

它适用于像这样的静态表:

<table id="table">
   <tr id="tr">
      <th><h4>uuid</h4></th>
      <th><h4>xValue</h4></th>
   </tr>
   <tr>
       <td><p>stuff2</p></td>
       <td><p>foo2</p></td>
   </tr>
   <tr>
       <td><p>stuff</p></td>
       <td><p>foo</p></td>
   </tr>
</table>

但是当我使用 ajax 从 json 动态创建表时,过滤脚本不再起作用。我该如何解决这个问题?

这是我使用的从 json 生成表的代码:

var url = 'https://api.github.com/users/mralexgray/repos';

$.ajax({
    type: 'GET',
    url: url,
    async: false,
    contentType: "application/json",
    dataType: 'json',
    crossDomain: true,
    success: function(data) {
        drawTable(data);
    },
    error: function(e) {
       console.log(e.message);
    }
});

function drawTable(data) {
    for (var i = 0; i < data.length; i++) {
        drawRow(data[i]);
    }
}

function drawRow(rowData) {
    var row = $('<tr/>')
    $("#table").append(row); //this will append tr element to table... keep its reference for a while since we will add cels into it
    row.append($("<td><p>" + rowData.id + "</p></td>"));
    row.append($("<td><p>" + rowData.name + "</p></td>"));
    row.append($("<td><p>" + rowData.lastName + "</p></td>"));
    row.append($("<td><p>" + rowData.private + "</p></td>"));
    row.append($("<td><p>" + rowData.fork + "</p></td>"));
    row.append($("<td><p>" + rowData.description + "</p></td>"));
    row.append($("<td><p>" + rowData.size + "</p></td>"));
}

【问题讨论】:

  • 你有没有得到任何错误,或者你得到了什么结果?

标签: jquery ajax filter html-table


【解决方案1】:

您在搜索功能之前定义$rows。设置后动态添加新行不会更改$rows 的值。尝试在搜索功能中定义它

$('#search').keyup(function() {
  var $rows = $('tr').not('#tr'); // set value here
  ..

【讨论】:

    猜你喜欢
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    相关资源
    最近更新 更多