【发布时间】: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