Handsontable 新增一行 默认值

效果图:

js,代码如下

/*

tpl数组为新增一行所给的默认值,没有的话为空''

*/

 

var
  tpl = ['one', 'two', 'three'],
  data = [
    ['', 'Kia', 'Nissan', 'Toyota', 'Honda'],
    ['2008', 10, 11, 12, 13],
    ['2009', 20, 11, 14, 13],
    ['2009', 30, 15, 12, 13]
  ],
  container = document.getElementById('example1'),
  hot1;
/*
*函数isEmptyRow为判断当前的行所述列是否为空,是返回true,
*/ function isEmptyRow(instance, row) {   var rowData = instance.getData()[row];   for (var i = 0, ilen = rowData.length; i < ilen; i++) {     if (rowData[i] !== null) {       return false;     }   }   return true; } /*
*函数 defaultValueRenderer 给当前行的列添加默认值
*/ function defaultValueRenderer(instance, td, row, col, prop, value, cellProperties) {
/*
* args 为获取当前列的属性
*/   var args = arguments; /*
*判断arg[5]的值是否为null,和空值(isEmptyRow,前面已经有相关函数做判断)
*符合条件的列赋值前面所给的数组的当前列的值tpl[col]
*/   if (args[5] === null && isEmptyRow(instance, row)) {     args[5] = tpl[col];     td.style.color = '#999';   }   else {     td.style.color = '';   }
/*
*判断arg[5]的值是否为undefined ,和空值(isEmptyRow,前面已经有相关函数做判断)
*符合条件的列赋值前面所给的数组的当前列的值tpl[col]
*/

if (args[5] === undefined && isEmptyRow(instance, row)) {
              args[5] = tpl[col];
              td.style.color = '#999';
            }
            else {
              td.style.color = '';
            }   Handsontable.renderers.TextRenderer.apply(this, args); } hot1 = new Handsontable(container, {   startRows: 8,   startCols: 5,   minSpareRows: 1,   contextMenu: true,
/*
*获取行的属性,执行defaultValueRenderer函数进行赋值
*/   cells: function (row, col, prop) {     var cellProperties = {};     cellProperties.renderer = defaultValueRenderer;     return cellProperties;   },
/*
*对当前table做操作前执行的函数,做相应的操作,这个我也没怎么看懂
*/   beforeChange: function (changes) {     var instance = hot1,       ilen = changes.length,       clen = instance.colCount,       rowColumnSeen = {},       rowsToFill = {},       i,       c;     for (i = 0; i < ilen; i++) {       // if oldVal is empty       if (changes[i][2] === null && changes[i][3] !== null) {         if (isEmptyRow(instance, changes[i][0])) {           // add this row/col combination to cache so it will not be overwritten by template           rowColumnSeen[changes[i][0] + '/' + changes[i][1]] = true;           rowsToFill[changes[i][0]] = true;         }       }     }     for (var r in rowsToFill) {       if (rowsToFill.hasOwnProperty(r)) {         for (c = 0; c < clen; c++) {           // if it is not provided by user in this change set, take value from template           if (!rowColumnSeen[r + '/' + c]) {             changes.push([r, c, null, tpl[c]]);           }         }       }     }   } }); hot1.loadData(data);

 

posted @ 2015-09-01 17:10  爱吃西红柿  阅读(5124)  评论(1编辑  收藏  举报