【发布时间】:2018-03-19 12:55:58
【问题描述】:
我正在尝试制作一个可编辑的表格,这样当用户单击“编辑”按钮时,每个表格数据单元格都会放置在用户可以输入和更改信息的输入表单中。用户完成后,他们可以再次单击编辑按钮,这样所有输入字段都会消失,所做的更改会保存并显示在表格上。
我已经做到了,当用户单击单个“编辑”按钮时,每个表格数据单元格中的每个数据都被放置在输入字段中。但是,我很难弄清楚如何删除输入框并显示所有更新的表格单元格。我正在考虑在每个 td 中放置“contenteditable”并将其更改为 true/false 会起作用,但我无法弄清楚。
我正在为此使用本地存储,但我只需要这件事上的帮助。任何帮助将不胜感激。
var retrieveContacts = localStorage.getItem("contacts");
var newVariable = JSON.parse(retrieveContacts);
var isEdit = 0; // is the table in edit mode? 0- false 1- true
// set to 0 (false) by default
$.each(newVariable, function(){
$('#tableStyles').append('<tr>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].email + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].firstname + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].lastname + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].prefix + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].title + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].company + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].phone + '</td>' +
'<td id="tableCells" contenteditable="false">' + newVariable[i].fax + '</td>' +
'</tr>');
i++;
});
$('#createCont').click(function(){
var newRow = "<tr style='height: 35px;'><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>";
$('#tableStyles').append(newRow);
newVariable.push({"email": "",
"firstname": "",
"lastname": "",
"prefix": "",
"title": "",
"company": "",
"phone": "",
"fax": ""});
localStorage.setItem("contacts", JSON.stringify(newVariable));
});
$('#editCont').click(function(){
if(isEdit == 0){
var j = 0;
var trCount = 2; // up to newVariable.length+1
var tdCount = 1; // up to 8
for(trCount; trCount < newVariable.length+2; trCount++){
for(tdCount; tdCount < 9; tdCount++){
var testing1 = $("tr:nth-child(" + trCount + ")").children("td:nth-child(" + tdCount + ")");
var testing2 = testing1.html("<input type='text' value='" + testing1.html() + "'/>");
}
tdCount = 1;
}
trCount = 2;
tdCount = 1;
isEdit = 1;
//console.log("isEdit set to 1");
} else if(isEdit == 1) { // if the edit button is clicked and we are already editing the form,
// then we have take out the input boxes and save all changes.
for(trCount; trCount < newVariable.length+2; trCount++){
for(tdCount; tdCount < 9; tdCount++){
var testing1 = $("tr:nth-child(" + trCount + ")").children("td:nth-child(" + tdCount + ")");
}
tdCount = 1;
}
isEdit = 0;
//console.log("isEdit set to " + isEdit);
}
});
【问题讨论】:
-
与您的问题无关,但
id="tableCells"id 必须是唯一的 - 您也永远不会将 contenteditable 设置为“true”,因此,不确定您为什么认为您可以编辑任何内容 -
我的错误,这是粗略的代码,我并没有完全打磨。表格单元格应该是一个类。
标签: javascript jquery html