参考了N多代码后实现的:
效果:点击添加按钮,向下添加一行,上一条操作变为删除
js代码
<script> $(function(){ addonetr(); }); function addonetr(){ $($("#table2 tbody")[0]).append("<tr><td align='center'>"+ "<select name='types'><option value=''>请选择</option>"+ "<option value='0'>单选题</option>"+ "<option value='1'>多选题</option>"+ "<option value='2'>问答题</option></select></td>"+ "<td align='center'><input type='text' size='45' value='' name='ques'/></td>"+ "<td align='center'><input type='text' size='45' value=''name='answ'/></td>"+ "<td align='center'><button name='delButton' οnclick='deltr(this);' class='btn1'>删除</button>"+ "<button name='addButton' οnclick='addonetr();' class='btn1'>添加</button></td></tr>"); $("button[name='delButton']").each(function(){ $(this).attr("style","display:block;"); }); $("button[name='delButton']:last").each(function(){ $(this).attr("style","display:none;"); }); $("button[name='addButton']").each(function(){ $(this).attr("style","display:none;"); }); $("button[name='addButton']:last").each(function(){ $(this).attr("style","display:block;"); }); try{event.returnValue=false;} catch(e){} }; //删除行的函数,必须要放domready函数外面 function deltr(delbtn){ $($(delbtn).parents("tr")[0]).remove(); }; </script>
html代码
<div> <form action="" method="post"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="100" height="35" align="right" valign="top" >问卷标题:</td> <td><input id="title3" type="text" name="title" size="70"/></td> </tr> <tr> <td width="100" height="35" align="right" valign="top" >发起单位: </td> <td><input type="text" name="title" size="70" id="initiator"/></td> </tr> <tr> <td width="100" height="35" align="right" valign="top" >问卷介绍: </td> <td><textarea rows="5" cols="100" name="context" id="descirbes"></textarea></td> </tr> <tr><td><br/></td></tr> <tr><td><br/></td></tr> <tr> <td width="100" height="35" align="right" valign="top">问卷内容: </td> <td> <table id="table2" border="1" border="0" cellspacing="0" cellpadding="0" width="89%"> <tbody> <tr> <td align="center" width="8%">题型</td> <td align="center" width="24%">问题</td> <td align="center" width="24%">答案</td> <td align="center" width="8%">操作</td> </tr> </tbody> </table> </table> </form> </div>