效果:点击控制显示隐藏按钮,将搜索框和添加按钮展示出来,点击添加按钮添加input框,点击input框后的删除按钮,删除对应的input框(设置当剩下最后一条input时,添加按钮隐藏)
1.引入jq的JS文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="./lib/jquery-min.js"></script>
<style>
#advancedSearch {
width: 100%;
background-color: #8ED0FF;
}
#advancedSearchBut {
width: 100px;
height: 50px;
border:1px solid red;
background-color: green;
}
.conditionBox{
position: relative;
display: flex;
}
.add,.delete{
width: 50px;
height: 50px;
margin-right: 20px;
border:1px solid yellowgreen;
}
.add{
position: absolute;
right: 1000px;
}
</style>
</head>
<body>
<div id="box">
<div id="advancedSearch">
搜索框
<div class="conditionBox" id="conditionBox">
<input type="text">
<button class="delete">删除</button>
</div>
</div>
<button class="add">添加</button>
<div id="advancedSearchBut">控制搜索框显示隐藏</div>
</div>
</body>
<script>
// 隐藏
$("#advancedSearch").hide();
$(".add").hide();
$('#advancedSearchBut').click(function () {
if ($("#advancedSearch").is(":hidden")) {
$("#advancedSearch").show(); //如果元素为隐藏,则将它显现
$(".add").show();
} else {
$("#advancedSearch").hide(); //如果元素为显现,则将其隐藏
$(".add").hide();
}
})
$('.delete').hide();
//删除
$("#box").on("click", ".delete", function () {
console.log($('#advancedSearch').find($(".conditionBox")).length);
$(this).parent().remove();
//判断页面中input框的数量
if ($('#advancedSearch').find($(".conditionBox")).length == 1) {
$('.delete').hide()
}
});
// 添加
$("#box").on("click", ".add", function () {
$('.delete').show()
//不能通过class类名 $('.conditionBox').clone() 来获取克隆元素,类名会将所有的带有类名的元素都克隆过来
var newObj = $('#conditionBox').clone()
console.log(newObj)
$("#advancedSearch").append(newObj);
})
</script>
</html>