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Wuf7ptee7a003wocyVg8rFtk9AhIj+zWUk+ve78/+/Fx72Z28EXge8ufx8fF4fLrg92dyMm2TStNWuV/78rnuWtWN8KGM1cOKRQgRkBrKnQjos3LCTe8F+Hz5nSY+98MUqnOXvl0EJLtrVTfChzJWDysWIURA0SqgvpL5QT8f4QLa/jLyEqpaLVwFTLYvcoOB1cOKRVB7AekRP7hV//7e9kYgcTvvd9jPo35/9jbQ9tgL6D3x3AjIdteaboQPZaweViwCe0cgc9Eb7I9vrNQ+f3qxn8uIeu8IDKxmR4Dlu2txN8KHMlYPKxbR/wugwLRyyG4G1sOKRRQBFJhWDtnNwHpYsYgigALTyiG7GVgPKxZRBFBgWjlkNwPrYcUiigAKTCuH7GZgPaxYRBFAgWnlkN0MrIcViygCKDCtHLKbgfWwYhEVEReiIrXn13qqR4AQgowiQIhTowgQ4tQoAoQ4NYoAIU6NIkCIU6MIEOLUKAKEODWKACFOjSJAiFOjCBDi1CgChDg1igAhTo0iQIhTUz0C/ifen9qDRByIIkBMU3uQiAP5D/E6LsRGbR6XAAAAAElFTkSuQmCC" alt="" />
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);