JavaScript – 通过input字段将对象添加到数组的末尾

我想dynamic地添加一个对象,使用JavaScript从一个input字段到数组的末尾。 唯一的问题是, 我正在尝试使用input字段 。 这是我想要发生的事情:

  1. 用户在文本字段中input某些内容
  2. 我的程序已经为它添加了一个唯一的ID
  3. 将它以对象的forms添加到数组的末尾
  4. 继续添加对象到该数组

这是我在我的JSON文件

{ "list": [{ "id": 0, "description": "Task #1 Description" }, { "id": 1, "description": "Task #2 Description" }, { "id": 3, "description": "Task #3 Description" }] } 

目前得到的是:

 { "list": [{ "id": 0, "description": "Task #1 Description" }, ] } 

每当我添加一个新的任务,它将取代已经在那里的那个。

这是我的JavaScript代码

  // 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.onclick = function() { id = indentification++; description = content.value; var task = { list: [] } task.list.push({id, description}); var jsonifyTask = JSON.stringify(task); fs.writeFile("tasks.json", jsonifyTask, "utf8"); } 

如果有人能帮助我,我将不胜感激 。 我花了几个小时试图弄清楚。 谢谢!

问题在这里:

 var task = { list: [] } task.list.push({id, description}); 

每次你做这个你的列表变空,然后添加新的项目。

改成这个

  // 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 } 
 // 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"); } 

有几件事你需要在这里考虑:

  1. 表单提交必须刷新页面并重置您的全局variables。 因此,您需要防止点击提交时的默认操作。

  2. (如前面的答案中所述)每次点击都会启动该列表。 您需要在onClick函数外初始化variables任务

     // 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"); } 

这应该有希望解决你的问题。