jq实现留言板的动态绑定发布及删除
思路:1.点击发布按钮, 动态创建一个小li,放入文本框的内容和删除按钮, 并且添加到ul 中。
2.点击的删除按钮,可以删除当前的留言。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0
}
ul {
list-style: none
}
.box {
width: 600px;
margin: 100px auto;
border: 1px solid #000;
padding: 20px;
}
.box span{
display: block;
padding: 10px;
}
textarea {
display: block;
width: 590px;
height: 140px;
outline: none;
resize: none;
}
.box button{
display: block;
width: 80px;
height: 40px;
background-color: cornflowerblue;
border: none;
color: #fff;
margin-top: 10px;
}
ul {
width: 450px;
padding-left: 80px;
}
ul li {
line-height: 25px;
border-bottom: 1px dashed #cccccc;
display: none;
}
input {
float: right;
}
ul li a {
float: right;
}
</style>
<script src="js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
// 1.点击发布按钮, 动态创建一个小li,放入文本框的内容和删除按钮, 并且添加到ul 中
/* 添加的几种方式
append() - 在被选元素的结尾插入内容(内部)
prepend() - 在被选元素的开头插入内容(内部)
after() - 在被选元素之后插入内容(外部)
before() - 在被选元素之前插入内容 (外部)*/
$(function(){
$(".btn").on("click",function() {
var li = $("<li></li>");
li.html($(".txt").val() + "<a href= 'javascript:;'> 删除</a>" );
if ($(".txt").val() == "") {
return false;
} else {
$("ul").prepend(li);
//可见的滑动隐藏
li.slideDown();
$("a").click(function(){
//绑定的a被选中后点击删除
$(this).parent().remove()
})
$(".txt").val("");
}
})
})
</script>
</head>
<body>
<div class="box" id="weibo">
<span>留言:</span>
<textarea name="" class="txt"></textarea>
<button class="btn">发布</button>
<ul>
</ul>
</div>
</body>
</html>
运行图片