前段时间因为域名关系网站停了一段时间。别的不多说了,我前端结合php做一个批量建栏目的模块,用到这个js效果
.今天拿出来和大家一起分享一下。看一下效果图:
对了下点,这个添加input动态添加 name也是可设成不同有,我用的是“text”+(1-100)之间的随机数字。最好就循环。这个好控制一下。
下面看一下HTML代码部分:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>无标题页</title>
<style type="text/css">
*{ padding:0px; margin:0px;}
.box{ width:170px; height:auto; margin:0px auto;
border:solid 1px #333333; margin-top:50px;
overflow:hidden;}
.kz{ width:100%; text-align: center;
line-height:30px; height:30px;
background:#999999;}
input{ display:inline;
margin-top:5px;}
#con{ text-align:center;
padding:5px 0px;}
</style>
</head>
<body>
<div class="box">
<div class="kz"><input type="button"
onclick="app()" value="添加" />
<input onclick="del()" type="button"
value="删除" /></div>
<div id="con">
</div>
</div>
</body>
</html>
再看一下javascript:
<script type="text/javascript">
var con=document.getElementById("con");
function app(){
var nu=Math.floor(Math.random() * (100-1)+1); //获取随机数字
var input=document.createElement("input"); //创建input标签
var br=document.createElement("br"); //
input.setAttribute("type","text");
input.setAttribute("name","text"+nu);
con.appendChild(input);
con.appendChild(br);
}
function del(){
var input=con.getElementsByTagName("input");
var br=con.getElementsByTagName("br");
var inputnu=input.length;
if(inputnu=="0"){
alert("不需要删除");
return;
}
con.removeChild(input[inputnu-1])
con.removeChild(br[inputnu-1])
}
</script>
这里主要用了dom的创建节点和创建节点属性、删除节点的函数。
document.createElement(
"input"
); //创建input标签
setAttribute("type"
,
"text"
);//
创建属性
con.removeChild(input[inputnu-1]) //删除节点
主要是这几个,别的大家可以看一下,反正很简单下面看一下DEMO
Demo:js动态添加表单
本文由 kevin 创作,采用 知识共享署名4.0 国际许可协议进行许可。
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。
