【问题标题】:Editing and Updating a HTML list with JavaScript使用 JavaScript 编辑和更新 HTML 列表
【发布时间】:2016-12-24 04:19:24
【问题描述】:

我正在尝试创建一个可以编辑/更新的列表。我需要能够将列表信息存储在某种变量中并在 HTML 页面上显示信息。

我的尝试是在下面的jsbin中。

JSBIN

https://jsbin.com/luxobineze/edit?html,js,console,output

因此,使用该代码,我想:

  • 通过填写表格并单击“添加名称”来添加名称
  • 点击[编辑],将填写要编辑的名称
  • 单击更新以更新全局变量“名称”(如果我可以这样做,那么我应该也可以更新 HTML 的“名称列表”)

我不确定在 updateName 函数中要做什么,因为我不确定如何将相关参数传递给它以更新正确的列表项。我是否需要使用更多全局变量来跟踪正在编辑的列表项?还是有更好、更标准的编码方式?

jsbin中的代码在这里:

HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
Name: <input type="text" id="name-input"><br>
<button id="add-name" class="button">Add Name</button>
<button id="update" class="button">Update</button>

<div id="list">List of Names</div>
</body>
</html>

JavaScript

// global variable storing the list of names
var names = [];

function addName() {
    var name = document.getElementById("name-input").value;
    var list = document.getElementById("list");

    if(name) {
        names.push("name");

        var wrapper = document.createElement("div")
        wrapper.setAttribute("id", name)

        var div_name = document.createElement("div");
        div_name.appendChild(document.createTextNode(name))

        var div_edit = document.createElement("div")
        div_edit.appendChild(document.createTextNode("[edit]"))
        div_edit.addEventListener("click", editName)

        wrapper.appendChild(div_name)
        wrapper.appendChild(div_edit)

        list.appendChild(wrapper)
    }
}

function editName() {
    // Fill the input box with the name that you want to edit
    var name = this.parentElement.getAttribute("id")
    document.getElementById("name-input").value = name;
}

function updateName() {
    var new_name = document.getElementById("name-input").value
    // How do I update the global variable "names"?

}

document.getElementById("add-name").addEventListener("click", addName)
document.getElementById("update").addEventListener("click", updateName)

编辑

我最终使用了一些全局变量来跟踪当前选择的项目:https://jsbin.com/zupawesifu/1/edit?html,js,console,output

【问题讨论】:

标签: javascript html


【解决方案1】:

听起来您正在构建最基本的应用程序,即 CRUD 应用程序。 (创建、读取、更新、删除)

将您的值存储在局部变量中并不是最理想的方式,除非这是您想要的功能。

你问“有没有更标准的方法”。更常见的方法是将您的值存储在数据库中,或者,在更简单的场景中,您可以将这些值存储在本地 .JSON 文件中。这将允许您随时使用您的应用程序、关闭应用程序、刷新或进行任何其他操作,而不会丢失您存储或编辑的值。

我不会在这里为您编写一个完整的 CRUD 应用程序,但这里有许多教程和模板供您学习。这是一个非常基本的。

我希望这会有所帮助!

http://mrbool.com/creating-a-crud-form-with-html5-local-storage-and-json/26719

【讨论】:

  • 是的,我正在尝试创建一个用于自学目的的 Chrome 扩展程序。我一直在使用 Chrome 的本地存储 API 以 JSON 格式保存所有数据,但我一直在纠结如何根据用户与 HTML 页面的交互来编辑/更新项目。我最终使用了更多的全局变量来跟踪选定的列表项,因此更新函数知道要更新什么:jsbin.com/luxobineze/4/edit?html,js,console,output 感谢该链接,我一定会查看它以了解正确的技术。
猜你喜欢
  • 2017-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多