【问题标题】:Table filter not working with backspaces表格过滤器不适用于退格
【发布时间】:2016-04-22 04:06:39
【问题描述】:

我正在努力根据http://docs.handsontable.com/0.15.0-beta6/demo-search-for-values.html 的内置搜索功能复制一个带有handsontable 的实时过滤器框。

现在我在http://jsfiddle.net/uL3L4teL/4/ 进行了基本设置

如文档中所述,在此代码中,如果您输入搜索字符串,则会使用以下函数将匹配的单元格输出到控制台:

Handsontable.Dom.addEvent(searchFiled, 'keyup', function (event) {
    var queryResult = hot.search.query(this.value);
    console.log(queryResult);
    // ...
});

我想在重新显示表格之前抓取数据数组中与搜索字符串匹配的行并通过搜索字符串过滤原始数据“数据”。这部分使用:

Handsontable.Dom.addEvent(searchFiled, 'keyup', function (event) {
  // debugger
  hot.loadData(tData);

  var queryResult = hot.search.query(this.value);
  rows = getRowsFromObjects(queryResult);
  console.log('searchFiled',searchFiled.value);
  console.log('rows',rows);

  console.log('tData', tData);
  var filtered = tData.filter(function (d, ix) {
      return rows.indexOf(ix) >= 0;
  });
  console.log('filtered', filtered);

  hot.loadData(filtered);

});

但是,当我运行此命令时,当我输入“n”后跟退格(以清空搜索字符串)时,我会在控制台中看到以下内容:

输入'n':

rows [0, 1]
searchFiled n
rows [0, 1]
tData [Array[4], Array[4], Array[4], Array[4]]
filtered [Array[4], Array[4]]

退格(清空搜索值):

rows []
searchFiled 
rows []
tData [Array[4], Array[4], Array[4], Array[4]]
filtered []

我该如何解决这个问题,以便空字符串再次显示整个未过滤的表?

【问题讨论】:

    标签: javascript jquery handsontable


    【解决方案1】:

    您可以在 .filter() 方法内添加一个条件,如果 searchFiled.value 的值为空或未定义,则该条件将返回所有行:

    Updated Example

    var filtered = tData.filter(function(_, index) {
      if (searchFiled.value) {
        return rows.indexOf(index) >= 0;
      } else {
        return true;
      }
    });
    

    或者,这里有一个做同样事情的单行代码(尽管它的可读性较差):

    Updated Example

    var filtered = tData.filter(function(_, index) {
      return !searchFiled.value || rows.indexOf(index) >= 0;
    });
    

    【讨论】:

    • !searchFiled.value 应更改为 searchFiles.value != '',否则 '0' 也会列出所有结果。
    • @noahnu 不,不会。变量searchFiled.value 是一个字符串。所有行都包含一个0,这意味着它们无论如何都会被选中。如果其中一行包含0,则不会全部选中。这是一个更新的示例,展示了这一点 -> jsfiddle.net/awyjnbj6
    • 谢谢乔希!我是 JS 新手,这里的主要问题是通过初始表加载没有发生的空字符串过滤吗?
    • @user61629 是的,这就是问题所在。当表格最初加载时,它没有被过滤,所以没有问题。在您提供的代码中,当按空字符串过滤时没有返回任何元素(这就是为什么我们添加条件以在字符串为空时返回 true)。
    猜你喜欢
    • 2018-09-13
    • 2020-12-26
    • 2015-07-12
    • 2013-01-20
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    相关资源
    最近更新 更多