2014-05-23 42 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中 - 它们将被解释为它们是输入的 –