我正在使用以下代码来编辑html表格(此代码可从在线教程链接获得:http://mrbool.com/how-to-create-an-editable-html-table-with-jquery/27425)。javascript可编辑表格无法正常工作
$("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事件。 问题是,即使我进行编辑(显示页面源显示原始内容),用于读取表格内容的函数也会显示原始内容。
谢谢
不是'$(this).parent().text(OriginalContent);'在“模糊”事件中,只需重新应用原始文本? –
问题似乎是$(this).parent()。text(newContent); $(this).parent()。text()返回空文本 – kostas
$(this).parent().text(OriginalContent)将恢复原始内容,如果用户编辑,然后不按回车 – kostas