我正在使用以下代碼來編輯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