gpt4 book ai didi

javascript 可编辑表格无法正常工作

转载 作者:行者123 更新时间:2023-12-03 12:33:36 26 4
gpt4 key购买 nike

我使用以下代码使 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 事件的回调。问题是,即使我进行编辑,用于读取表格内容的函数也会显示原始内容(显示页面源显示原始内容)。

谢谢

最佳答案

从.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();
}

关于javascript 可编辑表格无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23824922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com