<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JQ动态增加删除</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h3 style="margin: 0 auto;width: 200px">JQ动态增加删除表单项</h3>
<div id="main">
<ul id="ul" border="1" width="60%" align="center" style="margin-top:20px">
<li>
<span>0</span>
<input type="text" class="input" value="123">
<span style="cursor: pointer;"> <a id="but">增加</a></span>
</li>
</ul>
</div>
</body>
</html>
<style>
body {
margin: 0;
padding: 30px 10px;
}
#main {
border:1px solid red;
width: 600px;
margin: 60px auto;
}
li {
list-style: none;
width: 600px;
display: flex;
margin-bottom: 10px;
align-items: center;
}
li input {
display: flex;
flex-basis: 249px;
}
li span {
flex-basis: 129px;
}
</style>
<script>
$(document).ready(function(){
//增加<li>
$("#but").click(function(){
var addLength = $("#ul li").length;
$("#ul").append("<li id="+addLength+">"
+"<span>"+addLength+"</span>"
+"<input type='text' name='desc"+addLength+"' id='desc"+addLength+"' />"
+"<span><a href='#' onclick='del("+addLength+")' style='width: 100px; height: 30px;'>删除</a></span>"
+"</li>");
})
})
//删除<li>
var del =function(index){
var addLength = $("#ul li").length;
$("li[id='"+index+"']").remove();//删除当前行
for(var i=index+1,j=addLength;i<j;i++)
{
//replaceWith() 方法用指定的 HTML 内容或元素替换被选元素。
var nextVal = $("#desc"+i).val();
$("li[id=\'"+i+"\']")
.replaceWith("<li id="+(i-1)+" align='center'>"
+"<span>"+(i-1)+"</span>"
+"<input type='text' name='desc"+(i-1)+"' value='"+nextVal+"' id='desc"+(i-1)+"'/>"
+"<span><a href='#' onclick='del("+(i-1)+")'>删除</a></span>"
+"</li>");
}
}
</script>
Vue动态增加删除
查看:http://www.jq22.com/yanshi18211