我正在使用以下代码使html表格可编辑(此代码来自在线教程链接:http://mrbool.com/how-to-create-an-editable-html-table-with-jquery/27425)。
$("td").dblclick(function () {
//Obtain and record the value in the cell being edited. This value will be used later
var OriginalContent = $(this).text();
//Addition of class cellEditing the cell in which the user has double-clicked
$(this).addClass("cellEditing");
//Inserting an input in the cell containing the value that was originally on this.
$(this).html("<input type='text' value='" + OriginalContent + "' />");
//directing the focus (cursor) to the input that was just created, so that the user does not need to click on it again.
$(this).children().first().focus();
//the opening and closing function that handles the keypress event of the input.
//A reserved word this refers to the cell that was clicked.
//We use the functions first and children to get the first child element of the cell, ie the input.
$(this).children().first().keypress(function (e) {
//check if the pressed key is the Enter key
if (e.which == 13) {
var newContent = $(this).val();
$(this).parent().text(newContent);
$(this).parent().removeClass("cellEditing");
}
});
$(this).children().first().blur(function(){
$(this).parent().text(OriginalContent);
$(this).parent().removeClass("cellEditing");
});
});
似乎工作正常。然后我使用以下函数来读取表的内容并创建一个json表示:
function showRefTable(){
var headers = [];
var objects = [];
var headerRow = $('#dataTable thead tr');
var rows = $('#dataTable tbody tr');
headerRow.find('th').each(function(){
headers.push($(this).text());
});
for (var i=0; i<rows.length; i++){
var row = rows.eq(i);
var object = new Object();
for (var j=0; j<row.find('td').length; j++){
object[headers[j]] = row.find('td').eq(j).text();
}
objects.push(object);
}
var json = JSON.stringify(objects);
alert(json);
}
此函数用作onclick事件的回调。 问题是用于读取表格内容的功能即使我进行编辑也显示原始内容(显示页面源显示原始内容)。
由于
答案 0 :(得分:1)
从.text()读取表内容真的很糟糕。您将无法使用任何格式的数字和许多其他问题。每当用户更改值时,您最好将表内容保存在独立的数据对象中并从中重绘表。
我建议使用kendo grid - 它是功能强大,可靠的js表。
编辑:你的功能不起作用,因为你说你称之为onclick事件的回调。所以你在实际改变之前阅读了表的内容。 您应该在保存时阅读内容。在您的情况下,尝试在用户保存输入时调用您的功能(按Enter键) if (e.which == 13) {
var newContent = $(this).val();
$(this).parent().text(newContent);
$(this).parent().removeClass("cellEditing");
//Now, when content is changed, call your function
showRefTable();
}