2014-05-23 40 views
0

我正在使用以下代碼來編輯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事件。 問題是,即使我進行編輯(顯示頁面源顯示原始內容),用於讀取表格內容的函數也會顯示原始內容。

謝謝

+0

不是'$(this).parent().text(OriginalContent);'在「模糊」事件中,只需重新應用原始文本? –

+0

問題似乎是$(this).parent()。text(newContent); $(this).parent()。text()返回空文本 – kostas

+0

$(this).parent().text(OriginalContent)將恢復原始內容,如果用戶編輯,然後不按回車 – kostas

回答

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(); 
     } 
+0

但這不能回答我問題 – kostas

+0

看到我的編輯,我希望有幫助。但是,再次 - 不要使用這種內聯編輯。至少將內容保存在$(element).data中 - 它們將被解釋爲它們是輸入的 –