做下载后台的时候,做一个可以添加多个链接的功能。就是只要点击添加就会增加一个链接的输入框。这个功能是比较常用的,比如添加更多附件等等。做法是每次克隆一个tr,然后appendChild到table中。一开始死活没有效果,以为是语法有错。后来查看才知道,table无论有没有tbody,用appendChild都会生成tbody标签。appendChild到table的话,新增加的tr就会在</tbody>和</table>之间。
XML/HTML代码
- <TABLE id=link_tb cellSpacing=0 cellPadding=0 width="100%" border=0>
- <TBODY>
- <TR id=link_tr>
- <TD>URL: <INPUT size=55 name=link[url][]> <A style="DISPLAY: none" href="javascript:void(null);">删除</A> </TD>
- </TR>
- </TBODY>
- <TR>
- <TD>URL: <INPUT size=55 name=link[url][]> <A href="javascript:void(null);">删除</A> </TD>
- </TR>
- </TABLE>
所以要讲 tr appendChild 到 tbody 中就好了
XML/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>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>Downloads</title>
- <script language="javascript">
- window.onload = function(){
- window.new_link = $("link_tr").cloneNode(true);
- window.new_link.removeAttribute("id");
- window.new_link.getElementsByTagName("a")[0].style.display = "";
- }
- function $(id){
- return document.getElementById(id);
- }
- function more_link(){
- var newl = new_link.cloneNode(true);
- var a = newl.getElementsByTagName("a")[0];
- bind(a, "click", function(){delete_link(a);});
- $("link_tb").appendChild(newl);
- }
- function delete_link(o){
- while(o.parentNode){
- o = o.parentNode;
- if(typeof o.tagName != 'undefined' && o.tagName == 'TR'){
- o.parentNode.removeChild(o);
- break;
- }
- }
- }
- function bind(o, eventHandler, fun){
- if(o.attachEvent)
- o.attachEvent('on'+eventHandler,fun);
- else if(o.addEventListener)
- o.addEventListener(eventHandler,fun,false);
- }
- </script>
- </head>
- <body>
- <form action="" method="post" name="add_form">
- <table width="100%" border="0" cellspacing="0" cellpadding="0">
- <tbody id="link_tb">
- <tr id="link_tr">
- <td>URL: <input name="link[url][]" type="text" size="55" />
- <a href="javascript:void(null);" style="display:none;">删除</a>
- </td>
- </tr>
- </tbody>
- </table>
- </form>
- <a href="javascript:more_link()">继续添加地址</a>
- </body>
- </html>