我需要我的HTML表格可编辑,以便用户插入的数据可以被发送到服务器。 然而,由于该表的尺寸(50行),它不会是方便用户一个接一个插入的数据点,如果我介绍contenteditable
属性如下:
<table>
<tr><td><div contenteditable>editable</div></td><td><div contenteditable>editable</div></td></tr>
//...........
</table>
我怎样才能让我的表是可编辑的类似excel表格,如果可能的话,而无需使用道场等? 我一直在使用ExcelAdapter类在Java中做到了这一点。 有没有什么办法,我能做到这一点的HTML?
您可以将监听器添加到input
每个单元格的事件,如果单元格中包含多个数据项在接下来的细胞分裂他们。
function init()
{
var tables = document.getElementsByClassName("editabletable");
var i;
for (i = 0; i < tables.length; i++)
{
makeTableEditable(tables[i]);
}
}
function makeTableEditable(table)
{
var rows = table.rows;
var r;
for (r = 0; r < rows.length; r++)
{
var cols = rows[r].cells;
var c;
for (c = 0; c < cols.length; c++)
{
var cell = cols[c];
var listener = makeEditListener(table, r, c);
cell.addEventListener("input", listener, false);
}
}
}
function makeEditListener(table, row, col)
{
return function(event)
{
var cell = getCellElement(table, row, col);
var text = cell.innerHTML.replace(/<br>$/, '');
var items = split(text);
if (items.length === 1)
{
// Text is a single element, so do nothing.
// Without this each keypress resets the focus.
return;
}
var i;
var r = row;
var c = col;
for (i = 0; i < items.length && r < table.rows.length; i++)
{
cell = getCellElement(table, r, c);
cell.innerHTML = items[i]; // doesn't escape HTML
c++;
if (c === table.rows[r].cells.length)
{
r++;
c = 0;
}
}
cell.focus();
};
}
function getCellElement(table, row, col)
{
// assume each cell contains a div with the text
return table.rows[row].cells[col].firstChild;
}
function split(str)
{
// use comma and whitespace as delimiters
return str.split(/,|\s|<br>/);
}
window.onload = init;
演示: http://jsfiddle.net/yRnkF/
您可以通过添加轻松实现这个handsontable
更改任何股利一个excel表格
var $container = $("#divid");
$container.handsontable({
data: getData(),
rowHeaders: true,
colHeaders: true,
contextMenu: true //forces dom to use custom right click functionality like add row delete row add column etc
});
的jsfiddle: http://jsfiddle.net/jwtskyLa/
文章来源: How to make HTML table “Excel-like” editable for multiple cells, i.e. simultaneous copy-paste features?