<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 500px;
height: 300px;
margin: 50px auto;
}
.box textarea {
display: block;
width: 100%;
height: 150px;
outline: none;
}
.box div {
height: 50px;
}
.box button {
float: right;
width: 80px;
height: 30px;
outline: none;
border: none;
margin-top: 10px;
cursor: pointer;
}
ul li {
list-style: none;
border-bottom: 1px dashed orange;
font-size: 14px;
line-height: 35px;
}
ul li span {
float: right;
color: red;
cursor: pointer;
}
</style>
<script src="./tool.js"></script>
</head>
<body>
<div class="box">
<textarea></textarea>
<div><button>发送</button></div>
<ul>
</ul>
</div>
<script>
/*
// 1.获取元素 textarea button ul
// 2.button 绑定点击事件
+ 获取 textarea 的内容 判断是否填写了
+ 创建li
+ li里面还要设置内容 还有删除按钮
+ 插入到ul去
+ 清除多行文本里面内容
+ 绑定删除事件
*/
// 1. 获取元素
var txt = $('textarea')
var btn = $('button')
var ul = $('ul')
// 2.绑定点击事件
btn.onclick = function(){
// 2-1获取 textarea 的内容 判断是否填写了
var t1 = txt.value
if(!t1){
// 表示没有内容
return alert('请填写完整的内容!')
}
// 能走到这里 表示填写了
// 2-2 创建li
var li = document.createElement('li')
// 2-3 li里面还要设置内容 还有删除按钮
li.innerHTML = t1 + '<span>删除</span>'
// 2-4 插入到ul去
ul.insertBefore(li,ul.firstChild)
// 2-5 清除多行文本里面内容
txt.value = ''
// 2-6 绑定删除事件
// 获取所有的删除按钮 循环绑定事件
var spans = $('span',2)
// console.log(spans)
// 定义了一个当前作用域的i 遍历结束的时候 i变成了 length
for (var i = 0; i < spans.length; i ++){
// 点击的时候 循环早就已经结束了
spans[i].onclick = function(){
// console.log('点击了')
// console.log(i)
// console.log(this)
// 找到当前点击的span 然后找到父节点进行删除
this.parentNode.remove()
}
}
// console.log(spans)
}
</script>
</body>
</html>
使用一个js选择器的封装方法
/*
*获取元素
@params {String} name 表示css选择器
@params {Number} type 1 或者不传 表示选择一个 2 表示选择多个
@return 返回获取的元素
*/
function $(name, type) {
if (type == 2) {
return document.querySelectorAll(name)
} else {
return document.querySelector(name)
}
}