JavaScript实现列表的增删和移动
运行结果:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>列表的增删和移动</title>
<style>
.list-add {
color: #f60;
cursor: pointer;
}
.list-hide {
display: none;
}
</style>
</head>
<body>
<form>
<div id="list">
<ul id="list-ul" style="list-style: none">
<li>
<input type="text" name="list[]" value="PHP" readonly />
<span class="list-btn">
<span class="list-up" onclick="MoveUp(this)">[上移]</span>
<span class="list-down" onclick="MoveDown(this)">[下移]</span>
<span class="list-del" onclick="delete1(this)">[删除]</span>
</span>
</li>
</ul>
</div>
<div>
<div class="list-add"><span>+添加项目</span></div>
<div class="list-hide">
添加到列表:
<input id="list-add-input" type="text" />
<input id="list-add-add" type="button" value="添加" />
<input id="list-add-cancel" type="button" value="取消" />
</div>
</div>
</form>
<script>
let list_ul = document.getElementById("list-ul");
// 添加节点的方法
function add(input) {
// 克隆一个li节点
let li = list_ul.firstElementChild;
let newli = li.cloneNode(true);
newli.firstElementChild.value = input;
list_ul.appendChild(newli);
}
// 添加项目事件
let list_add = document.querySelector("div.list-add");
list_add.onclick = () => {
// 显示list-hide
let list_hide = document.querySelector("div.list-hide");
list_hide.style.display = "inline";
};
// 添加按钮事件
let list_add_add = document.getElementById("list-add-add");
list_add_add.onclick = () => {
// 取出list-add-input的值
let input = document.getElementById("list-add-input");
if (input.value.trim() == "") {
alert("请输入内容!");
return;
}
add(input.value);
input.value = "";
};
// 取消按钮事件
let list_add_cancel = document.getElementById("list-add-cancel");
list_add_cancel.onclick = () => {
// 隐藏list-hide
let list_hide = document.querySelector("div.list-hide");
list_hide.style.display = "none";
};
// 上移事件
function MoveUp(obj) {
// 查找所属的祖先节点li
let movenode = obj.parentNode.parentNode;
let prev = movenode.previousElementSibling;
// 判断是否为第一个
if (prev != null) {
// 上移
list_ul.insertBefore(movenode, prev);
}
}
// 下移事件
function MoveDown(obj) {
let movenode = obj.parentNode.parentNode;
let downnode = movenode.nextElementSibling;
if (downnode != null) {
list_ul.insertBefore(downnode, movenode);
}
}
// 删除事件
function delete1(obj) {
let delnode = obj.parentNode.parentNode;
list_ul.removeChild(delnode)
}
// 初始化列表
add("JavaScript"); // 添加节点的方法
</script>
</body>
</html>