html与css代码
<style>
.wrapper{
width: 700px;
margin: 0 auto;
}
h2{
background-color: lightgray;
text-indent: 20px;
height: 70px;
line-height: 70px;
}
.submit{
margin-left: 180px;
margin-top: 20px;
}
.wrapper>div:nth-of-type(2){
display: flex;
}
.reply{
margin-left: 50px;
}
ul>li{
width: 350px;
height: 50px;
line-height: 50px;
border: 1px solid gray;
margin-bottom: 10px;
border-radius: 5px;
padding: 10px;
}
li>span:nth-of-type(1){
font-size: 14px;
}
li>span:nth-of-type(2){
font-size: 12px;
}
.del{
float: right;
}
</style>
</head>
<body>
<div class="wrapper">
<div>
<h2>欢迎来到吐槽大厅</h2>
</div>
<div>
<div class="user">
<div>用户名</div>
<input type="text" class="username" placeholder="用户名">
<div>吐槽内容</div>
<textarea name="" class="contain" cols="30" rows="10" placeholder="吐槽内容"></textarea>
<br>
<button class="submit">提交</button>
</div>
<div class="reply">
<div>吐槽回复:</div>
<ul>
<!-- li>
<span>TOM说</span><span>:妈妈,我要吃烤山药</span><button class="del">删除</button>
</li> -->
</ul>
</div>
</div>
</div>
js阶段
$(function(){
$(".submit").click(function(){
submitInfo();
showInfo();
})
$("ul").on("click",".del",function(){
delInfo();
showInfo();
})
var userArr;
//提交操作
function submitInfo(){
userArr=localStorage.userList==undefined?[]:JSON.parse(localStorage.userList);
var username=$(".username").val();
var contain=$(".contain").val();
//封装对象放入数组
var obj={
username: username,
contain:contain
}
//添加到数组
userArr.push(obj)
//重新更新到本地
localStorage.userList=JSON.stringify(userArr);
$(".username").val("");
$(".contain").val("");
}
//渲染操作
showInfo();
function showInfo(){
$("ul").html("");
userArr = localStorage.userList == undefined ? [] : JSON.parse(localStorage.userList);
userArr.forEach(obj=>{
$("ul").prepend(`<li>
<span>${obj.username}说</span>
<span>:${obj.contain}</span>
<button class="del">删除</button>
</li>`)
})
}
//删除操作
function delInfo(){
var contain=$(this).parent().html();
var index=userArr.indexOf(contain);
//删除当前数据
userArr.splice(index,1);
console.log(userArr.splice(index,1));
localStorage.userList=JSON.stringify(userArr);
}
})