javascript - 如何在 Handsontable 的 afterChange 中使用 getCellMeta?

标签 javascript jquery hook handsontable

我正在使用 handsontable js插件。我想使用 getCellMeta 函数在 afterChange Hook 但不工作。 我在 afterChange Hook 中使用函数时,函数正在运行。但在 afterChange Hook 中不起作用。

var container = document.getElementById('t1'),
  options = document.querySelectorAll('.options input'),
  table,
  hot; 

hot = new Handsontable(container, {    
  autoWrapRow: true,
  startRows: 81,
  startCols: 206,
  autoColumnSize : true,  
  stretchH: 'all', 
  afterChange : function(change,source) { 
      if (source === 'loadData') {
        return;
      }   
      var test = this.getCellMeta(change[0],change[1]); // not working, not return "id" meta
      console.log(test);  
  }
});

$.ajax({
  url: 'path',
  type: 'GET',
  dataType: 'json',
  success: function (res) { 
    var data = [], row, pc = 0; 
    for (var i = 0, ilen =  hot.countRows(); i < ilen; i++)
    {
      row = []; 
      for (var ii = 0; ii<hot.countCols(); ii++)
      {   
        hot.setCellMeta(i,ii,'id',res[pc].id);
        row[ii] =   res[pc].price;
        if(pc < (res.length-1)) {

        pc++;
        }
      } 
      data[i] = row;
    }  
    hot.loadData(data);
  }
}); 

var test = this.getCellMeta(0,0); // is working, return "id" meta
console.log(test);  

我在更改后尝试的输出控制台日志; enter image description here

在afterChange中输出控制台日志使用; enter image description here

如何获取改变后的cell meta?

谢谢。

最佳答案

您快完成了,您的回调中只有一个小错误:doc for afterChange指定回调的第一个参数 (changes) 是:

a 2D array containing information about each of the edited cells [[row, prop, oldVal, newVal], ...].

因此,2 个重要细节:

  • 要获取受影响单元格的行/列的“元”(假设只有一个),您需要调用 hot.getCellMeta(change[0][0],change[0][1] ) 例如
  • hot 而不是 this 因为 afterChange 回调函数是从不同的上下文调用的(即在不同的对象上),所以 this 不是调用的正确目标,请参阅 How does the "this" keyword work?

读取整个更改数组的示例:

var hot = new Handsontable(container, {
  /* rest of init... */
  afterChange : function(changes,source) {
      console.log("Changes:", changes, source);
      if (changes) {
          changes.forEach(function(change) {
              var test = hot.getCellMeta(change[0],change[1]);
              console.log(test.id, test); // 'id' is the property you've added earlier with setMeta         
          });
      }
  }
});

参见 demo fiddle ,打开 JS 控制台,在表中进行任何更改。

关于javascript - 如何在 Handsontable 的 afterChange 中使用 getCellMeta?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47965692/

相关文章:

C++ 在 Exe 中修补调用

macos - Mac 钩子(Hook)函数

javascript - 保护亚马逊存储桶中的 json 数据

javascript - 如何使用 Express 在 Node.js 中打印响应主体(或 POST 时的请求主体)?

javascript - 如何在表格单元格(td)上使用 Bootstrap 的下拉菜单?

javascript - jQuery inArray 函数在更改选择时不获取值

php - 带有 WooCommerce add_actions 的 Wordpress 不起作用

javascript - 欧芹阻止输入验证时提交

asp.net - 如何将 JavaScript 直接嵌入到我的 ASP.net 自定义控件中?

javascript - 添加链接时 Bootstrap 下拉按钮将不起作用