<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>简易留言板</title>
</head>
<body>
<h4>YY留言板</h4>
<div id="box">
</div>
<textarea id="msg"></textarea>
<input type="button" id="btn" value="留言">
<button type="button" onclick="count()">统计留言数</button>
</body>
<script type="text/javascript">
var ul=document.createElement("ul");
var box=document.getElementById("box");
box.appendChild(ul);
var counts=0;
var btn=document.getElementById('btn');
var msg=document.getElementById('msg')
btn.onclick=function (ev) {
var content=msg.value;
var li=document.createElement('li')
li.innerHTML=content+"<span> X</span>";
var lis=document.getElementsByTagName("li");
if(lis.length==0){
ul.appendChild(li);
counts++;
}else {
ul.insertBefore(li,lis[0]);
counts++;
}
msg.value="";
//添加li标签后动态给设置onclick属性
var spans=document.getElementsByTagName("span");
for(i=0;i<spans.length;i++){
spans[i].onclick=function () {
ul.removeChild(this.parentNode);
counts--;
}
}
};
function count() {
alert("一共发布了"+counts+"条留言");
};
</script>
</html>