示例地址
html部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>todolist</title>
</head>
<body>
<script src="todo.js"></script>
<label for="todo">
<input type="text" name="todo" id="todo" placeholder="请输入事项" autofocus>
</label>
<button type="submit" onclick="add()">提交</button>
<ul class = 'list'>
</ul>
</body>
</html>
JS部分
//找到节点获取内容容器
let ul= document.querySelector('.list');
function add () {
let ul= document.querySelector('.list');//注释掉此行,21行提示报错为: Uncaught TypeError: Cannot read properties of null
//获取表单元素的值
let items = document.querySelector('#todo');
// console.log(items.value);
// console.log(items.value.length);
//空值判断
if (items.value.trim().length===0){
alert('内容不能为空');
items.focus()
}
//创建li元素
let li = document.createElement('li');
//将input的值赋给li元素
li.innerHTML = items.value + ` `+'<button onclick="del(this.parentNode)">删除</button>';
// li.textContent ='item.value';
//将li元素追加到ul下面
ul.insertAdjacentElement('afterBegin', li);
console.log(li);
// ul.after(li);
//清空输入框
items.value=null;
//焦点重置
items.focus();
}
let del = function (items) {
//删除确认
confirm ('删除确认')?items.remove():false;
//删除后自动获取焦点
let it = document.querySelector('#todo');
it.focus()
}