在文本框中输入想要留言的内容,点击留言按钮实现留言,点击删除实现删除
<!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>
<script>
window.onload=function(){
var oTxt=document.getElementById('txt');
var oBtn=document.querySelectorAll('input')[1];
var oUl=document.getElementById('ul');
oBtn.onclick=function(){
var str=oTxt.value;
var oLi=document.createElement("li");
oLi.innerHTML=str;
var oBtn2=document.createElement("button");
console.log(oBtn2)
oBtn2.style.border='none';
oBtn2.innerHTML='删除';
// 把button追加到li中
oLi.appendChild(oBtn2);
// 点击事件
oBtn2.onclick=function(){
//删除此button的父节点
oUl.removeChild(this.parentNode);
}
// ul里是否存在第一个元素节点
if(oUl.children[0]){
// 在第一个节点前插入
oUl.insertBefore(oLi,oUl.children[0]);
}else{
oUl.appendChild(oLi);
}
oTxt.value=null;//清空文本框
}
}
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" value="留言">
<ul id="ul"></ul>
</body>
</html>