我正在尝试动态使用JavaScript将带有输入字段值的对象添加到数组末尾。唯一的问题是我正在尝试使用输入字段。这就是我想要发生的事情:
这是 JSON文件中我想要的:
let a = ["a", "bc", "def"]
let nsa = NSArray(array: a)
nsa[0] is NSString // *** true ***
我目前正在 :
{
"list": [{
"id": 0,
"description": "Task #1 Description"
}, {
"id": 1,
"description": "Task #2 Description"
}, {
"id": 3,
"description": "Task #3 Description"
}]
}
每次添加新任务时,都会替换已存在的任务。
以下是我的 JavaScript代码:
{
"list": [{
"id": 0,
"description": "Task #1 Description"
}, ]
}
如果有人能帮助我,我会非常感激它。我花了小时试图解决这个问题。谢谢!
答案 0 :(得分:2)
问题在于:
var task = {
list: []
}
task.list.push({id, description});
每次执行此操作时,您的列表将变为空,然后添加新项目。
答案 1 :(得分:2)
更改为
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
var task = {
list: []
}
submit.onclick = function() {
id = indentification++;
description = content.value;
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8"); // what're you doing here, browser do not allow write file to disk
}
答案 2 :(得分:1)
您需要在此处考虑以下几点:
表单提交必须刷新页面并重置全局变量。因此,您需要阻止点击提交时的默认操作。
(如前面的答案所述)每次点击都会启动该列表。您需要在onClick函数
之外初始化变量任务// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
//initialize outside the on click function
var task = {
list: []
}
submit.onclick = function(e) {
//This prevents page refresh on form submission and preserves the global variable states
e.preventDefault();
id = indentification++;
description = content.value;
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8");
}
这有望解决您的问题。
答案 3 :(得分:0)
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
submit.addEventHandler("click", function() {
id = indentification++;
description = content.value;
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8");
}