微博发布评论,评论区动态增加刚发布的内容,并提供删除功能。练习创建节点、追加节点、移除节点。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>微博发布</title>
<style>
ul{
margin: 0;
padding: 0;
list-style: none;
}
.box{
width: 500px;
height: auto;
margin: 100px auto;
border: 1px solid #eee;
padding: 10px 0;
}
.box textarea{
width: 300px;
height: 200px;
resize:none;
}
.commands{
margin-left: 90px;
}
.commands li{
width: 300px;
height: 30px;
line-height: 30px;
border-bottom: 1px dashed #666;
}
.commands li a{
float: right;
}
</style>
<script>
window.onload = function(){
function $(id){ return document.getElementById(id); }
$("btn").onclick = function(){
if($('txt').value==""){
alert("输入内容不能为空");
return;
}else{
var newli = document.createElement("li");
newli.innerHTML = $('txt').value + "<a href='javascript:;'>删除</a>";
var childrens =$('ul').children;
if(childrens.length==0){
$('ul').appendChild(newli);
}else{
$('ul').insertBefore(newli,childrens[0]);
}
$('txt').value = "";
}
var as = $("ul").getElementsByTagName("a");
for(var j=0; j<as.length; j++){
as[j].onclick = function(){
$('ul').removeChild(this.parentNode);
}
}
}
}
</script>
</head>
<body>
<div class="box">
<div class="write">
微博发布:
<textarea name="" id="txt" cols="30" rows="10"></textarea>
<button id="btn">发布</button>
</div>
<ul id="ul" class="commands">
<!-- <li>123</li>
<li>asdf</li>
<li>wqe2</li> -->
</ul>
</div>
</body>
</html>