完成案例:
HTML代码:
<div class="welcome">
<h1>欢迎来到吐槽大会</h1>
</div>
<div class="wrapper">
<div class="user">
<span>用户名</span><br>
<input type="text" placeholder="用户名" id="username"><br>
<span class="tc_conrain">吐槽内容</span><br>
<textarea id="test_contain" cols="35" rows="3" placeholder="吐槽内容"></textarea><br>
<button id="submit">提交</button>
</div>
<div class="right_box">
<h2>吐槽回复</h2>
<ul>
</ul>
</div>
</div>
//这个是jquery的js文件,可以去官网下载的
<script src="./jquery-3.6.0.js"></script>
<script src="./1、吐槽大会.js"></script>
css代码
*{
margin: 0;
padding: 0;
}
ul{
list-style: none;
}
a{
text-decoration: none;
font-size: 13px;
color: #74B1D5;
}
i{
font-style: normal;
}
.wrapper{
width: 1000px;
margin: 0 auto;
padding: 0px 20px;
display: flex;
box-sizing: border-box;
justify-content: space-around;
/* border: 1px solid black; */
}
.user{
position: relative;
width: 300px;
}
input{
width: 268px;
height: 30px;
}
.user span{
font-size: 13px;
font-weight: bold;
display: inline-block;
margin-top: 15px;
margin-bottom: 5px;
}
#username,#test_contain{
text-indent: 20px;
outline: none;
}
#test_contain{
padding-top: 10px;
}
button{
display: block;
margin-left: 230px ;
margin-top: 15px;
}
.right_box{
width: 550px;
}
li{
display: flex;
padding: 0px 15px;
height: 50px;
justify-content: space-between;
line-height: 50px;
border: 1px solid #E5E5E5;
font-size: 13px;
color: #585655;
border-radius: 3px;
}
.username{
font-size: 15px;
}
.welcome{
width: 1000px;
margin: 0 auto;
height: 100px;
line-height: 100px;
background-color: lightgray;
text-align: center;
}
js代码
$(function(){
var nextID3 = localStorage.nextID3 || 0;
var arr ;
//点击提交按钮
$("#submit").click(function(){
if($("#username").val()!= "" && $("#test_contain").val() != ""){
// alert("吐槽内容不能为空!")
// return
arr = getinfo();
//将数据饭放入数组里面
var obj = {
nextID3 :nextID3++,
name : $("#username").val(),
contain : $("#test_contain").val()
}
arr.unshift(obj)
//清空输入框
$("#username").val("")
$("#test_contain").val("")
//更新数据
upadteinfo()
//渲染数据
showinfo()
}
})
//渲染数组
showinfo()
function showinfo(){
arr = getinfo();
//渲染前先清空
$("ul").html("");
arr.forEach(item =>{
// 创建节点
$("ul").prepend(`<li data-id = "${item.nextID3}">
<div class="li_left">
<span class="username"><i>${item.name}</i>说:</span>
<span class="test">${item.contain}</span>
</div>
<a href="javascript:void(0);" class="del">删除</a>
</li>`);
})
}
//删除
$("ul").on("click",".del",function(){
if(confirm("确定删除吗?")){
arr = getinfo();
//通过id找到数组
var id3 = $(this).parent().attr("data-id");
var index = arr.findIndex(item=>{
return id3==item.nextID3;
})
arr.splice(index,1);
//重新更新到本地
localStorage.tclist = JSON.stringify(arr);
showinfo()
}
})
//判断是否有数组
function getinfo(){
return localStorage.tclist==undefined ? [] : JSON.parse(localStorage.tclist)
}
//更新数据
function upadteinfo(){
//更新数组
localStorage.tclist = JSON.stringify(arr);
//更新nextID3
localStorage.nextID3 = nextID3;
}
})