關於表格動態添加行並處理相關表單元素的一些修改


源碼參照修改自網上,主要的修改如下:

1.處理了動態行與表單的設值問題
2.添加了行的向上或向下排序
3.添加了可以在當前行的下邊或上邊增加新行的功能
4.添加了可以單選或勾選多項刪除不需要的行的功能
5.添加了新增的行的高亮(以new紅標記標注)的功能
6.實現了可以不依靠樣式表(即:即使不要<style></style>部分,功能不會一點)
7.實現了方便后端的接收的數據形式(通過一個動態的長度設置,后端獲取這個動態長度並且從1開始循環即可接收相關數據)
8.實現了方便后端進行編輯時的界面(即添加與編輯的頁面的js代碼部分完全不用更改!)



  注意:本文中的代碼存在很多冗余,已經進行了修改.修改后的地址:  

     http://www.cnblogs.com/dreamyoung/p/4064479.html

效果圖如下:                   預覽效果   (有css樣式)

                               預覽效果   (無css樣式)

其它效果圖:

 

 



好了.放上代碼,代碼只有三個部分(HTML部分,JS部分,CSS部分,其中CSS部分可省略)

HTML部分:

<!--注意:為了兼容chrome瀏覽器對動態表格行的表單數據能正常提交到服務器端,<form>標簽必須放置在<table>外圍-->
<form id="submitform" method="get" target="_blank">
<table id="tab" border="1" width="60%" align="center" style="margin-top:20px" cellspacing="0" cellpadding="0">
        <tr id='thead'>
        <td nowrap="nowrap" width="40"><input type='checkbox' id='delckall' /></td>
            <td nowrap="nowrap" width="80">序號</td>
            <td nowrap="nowrap" width="140">標題<span style='color:red;font-weight:normal'>*</span></td>
            <td nowrap="nowrap" width="100">類型<span style='color:red;font-weight:normal'>*</span></td>
            <td nowrap="nowrap" width="100">附加選值</td>
            <td nowrap="nowrap" width="100">默認值</td>
            <td nowrap="nowrap" width="140">輸入提示</td>
            <td nowrap="nowrap" width="140">操作</td>
            <td nowrap="nowrap" width="140">排序</td>
       </tr>



    </table>
    <input type="hidden" name="inputlen" value="0" id="inputlen"/>
    <div id="tbtoolbar" align="center">
    <span class="blocktip">說明:對於附加選值,請用<span style="color:#f80">|</span>號隔開多個值.對於多選框的默認值如果有多個請用<span style="color:#f80">|</span>號隔開</span>
       <input class="btnclass" type="button" id="but" value="增加一個"/>
           <input class="btnclass" type="button" id="submitbtn" value="提交看行數"/>

           <input class="btnclass" type="button" id="delbtn" value="刪除選定的行數"/>
   </div>
  </form>


JS部分:

<script src='jquery.js'></script>
<script>
   $(document).ready(function(){
        newtrtemp = function(index) {
            var tr =  "<tr id="+index+" align='center'>"
                                +"<td><input type='checkbox' id='delck_"+index+"' /></td><td nowrap='nowrap'><div class='countnum' style='position:relative'>"+index+"<div class='newdot' id='new_"+index+"' style='color:red; font-size:12px;display:none;position:absolute;top:-8px; right:0px;'>new</div></div></td>"
                               +"<td><input type='text' name='inputFtitle"+index+"' id='inputFtitle"+index+"' value='標題"+Math.floor(Math.random()*(10000000-1000000)+1000000)+"'/></td>"
                               +"<td><select onchange='changeBH(this);' name='inputFtype"+index+"' id='inputFtype"+index+"'><option value='文本框' selected='selected'>文本框</option><option value='文本域'>文本域</option><option value='下拉框'>下拉框</option><option value='單選框'>單選框</option><option value='多選框'>多選框</option><option value='上傳框'>上傳框</option></select></td>"
                               +"<td nowrap='nowrap'><div id='changetext"+index+"' style='display:'><span style='color:#CCCCCC;font-weight:normal'>暫無</span></div><div id='changeselect"+index+"' style='display:none;'><input type='text' name='inputFselect"+index+"' id='inputFselect"+index+"' size='20' /><span style='color:red;font-weight:normal'>*</span></div></td>"
                               +"<td><input type='text' name='inputFdefault"+index+"' id='inputFdefault"+index+"' size='10'/><span style='color:#CCCCCC;font-weight:normal'></span></td>"
                               +"<td><input type='text' name='inputFtip"+index+"' id='inputFtip"+index+"' /></td>"
                               +"<td nowrap='nowrap'><a href=\'#\' onclick=\'deltr("+index+")\'>刪除</a>&nbsp;&nbsp;<a href=\'#\' onclick=\'addnexttr("+index+")\'>下增</a>&nbsp;&nbsp;<a href=\'#\' onclick=\'addnexttr("+(index-1)+")\'>上增</a></td><td><a href=\'#\' onclick=\'moveup("+index+")\' id='moveup_"+index+"'>向上</a>&nbsp;&nbsp;<a id='movedown_"+index+"' href=\'#\' onclick=\'moveup("+(index+1)+")\'>向下</a></td>"
                           +"</tr>";
                
                return tr;
        }
        
        
        //此行用於模擬服務器提交獲取的數據
        if(window.location.search!="") {$('#submitform').append('<p>服務器接收到的表單信息為:<br/>'+window.location.search+"</p>");}
        
        
        //表單提交時的事件
        $("#submitbtn").click(function(){
            $("#submitform").append('<br/>輸入的行數為:'+$("#inputlen").val()+",即inputLen="+$("#inputlen").val()+"<br/>您可以在服務器端通過循環由1到inputLen獲取表單數據,比如inputFtitle[inputLen]即為第inputLen個標題輸入項&nbsp;&nbsp;&nbsp;&nbsp; <a href='#' onclick='document.getElementById(\"submitform\").submit();'>查看提交的表單數據</a>");
            return false;
        });

        
        //全選反選處理
        var allchecked = false;
        $("#delckall").click(function(){
            allchecked = !allchecked; 
            for(var i=$("#inputlen").val()-0 ;i>=1; i--) {
                $("#delck_"+i)[0].checked = (!allchecked) ? false : 'checked';
                
            }
        });

        //批量刪除處理
        $("#delbtn").click(function(){
            for(var i=$("#inputlen").val()-0 ;i>=1; i--) {
                if($("#delck_"+i)[0].checked) {
                    var delsometr = function(index) {
                        deltr(index);
                    }

                    delsometr(i);    //刪除單行
                }
            }
            return false;
        });


        var tablejquery = '#tab'    //<table>的id設置,方便重用
        
        //設置所有的<tr/>居中
        $(tablejquery+" tr").attr("align","center");
       
        
        //用於限制向上向下時的超界問題
       var moveupHTML = "<a href=\'#\' onclick=\'moveup($k$)\' id='moveup_$k$'>向上</a>"
       var movedownHTML = "<a id='movedown_$k$' href=\'#\' onclick=\'moveup($k+1$)\'>向下</a>"
        //設置鏈接無效,供添加刪除等調用
       disableHref = function() {
         var trlen = $(tablejquery+' tr').length;
         $(tablejquery+' tr').each(function(k,v) {
                //將所有的樣式及限制還原
                if(k>0 && k< trlen) {
                    $('#moveup_'+k).replaceWith(moveupHTML.replace("$k$",k).replace("$k$",k));
                    $('#movedown_'+k).replaceWith(movedownHTML.replace("$k$",k).replace("$k+1$",(k+1)));
                }

                //單獨設置限定項
                if(k==1){
                    $('#moveup_'+k).replaceWith("<span style='font-weight:lighter;color:#CCC;font-size:12px;' id='moveup_"+k+"'>向上</span>");
                }

                if(k+1==trlen) {
                    $('#movedown_'+k).replaceWith("<span style='font-weight:lighter;color:#CCC;font-size:12px;' id='movedown_"+k+"'>向下</span>");
                }
         });
       }
       
       
       //在尾部新增加一項<tr/>
      $("#but").click(function(){
         //隱藏new效果                       
         $('.newdot').hide();
          var _len = $(tablejquery+" tr").length;        
          $(tablejquery).append(newtrtemp(_len)); 

          //設置新增項有new效果
          $('#new_'+_len).show();
          
          //設置服務器的獲取長度
          $('#inputlen').val($(tablejquery+" tr").length-1);
           //向上及向下的界限處理
           disableHref();
           
            return false;
        })  
    
    
    // 將第i行的內容設置到第j行.即tr(id=i).replaceWith(tr(id=j))
    var MoveTr = function(fromIndex,toIndex,keep) {
        var i = fromIndex;
        var j = toIndex;
        var k = keep //是否保留原先的tr,如果keep=false,則原tr被替換沒掉了
        
        //獲取當前項的表單值
            var nextTxtVal = $("#inputFtip"+i).val();
            var nextTitleVal = $("#inputFtitle"+i).val();
            var nextSelectVal = $("#inputFselect"+i).val();
            var inputFtypeCK1 = $("#inputFtype"+i)[0].options[$("#inputFtype"+i)[0].selectedIndex].value !== '文本框' ? '': ' selected=\""+selected+"\"';
            var inputFtypeCK2 = $("#inputFtype"+i)[0].options[$("#inputFtype"+i)[0].selectedIndex].value !== '文本域' ? '': ' selected=\""+selected+"\"';
            var inputFtypeCK3 = $("#inputFtype"+i)[0].options[$("#inputFtype"+i)[0].selectedIndex].value !== '下拉框' ? '': ' selected=\""+selected+"\"';
            var inputFtypeCK4 = $("#inputFtype"+i)[0].options[$("#inputFtype"+i)[0].selectedIndex].value !== '單選框' ? '': ' selected=\""+selected+"\"';
            var inputFtypeCK5 = $("#inputFtype"+i)[0].options[$("#inputFtype"+i)[0].selectedIndex].value !== '多選框' ? '': ' selected=\""+selected+"\"';
            var inputFtypeCK6 = $("#inputFtype"+i)[0].options[$("#inputFtype"+i)[0].selectedIndex].value !== '上傳框' ? '': ' selected=\""+selected+"\"';
                
            var displayText = $('#changeselect'+i)[0].style.display == 'none' ? '' : 'none';
            var displaySelect = $('#changeselect'+i)[0].style.display == 'none' ? 'none' : '';
            var nextDefaultVal = $("#inputFdefault"+i).val();
            
            //將當前項(包括表單項值等)設置到第j項項
            $("tr[id=\'"+(k? j : i)+"\']")
                       .replaceWith("<tr id="+j+" align='center'>"
                                       +"<td><input type='checkbox' id='delck_"+j+"' /></td><td nowrap='nowrap'><div class='countnum' style='position:relative'>"+j+"<div class='newdot' id='new_"+j+"' style='color:red; font-size:12px;display:none;position:absolute;top:-8px; right:0px;'>new</div></div></td>"
                                        +"<td><input type='text' name='inputFtitle"+j+"' value='"+nextTitleVal+"' id='inputFtitle"+j+"'/></td>"
                                          +"<td><select onchange='changeBH(this);' name='inputFtype"+j+"' id='inputFtype"+j+"'><option value='文本框'"+inputFtypeCK1+">文本框</option><option value='文本域'"+inputFtypeCK2+">文本域</option><option value='下拉框'"+inputFtypeCK3+">下拉框</option><option value='單選框'"+inputFtypeCK4+">單選框</option><option value='多選框'"+inputFtypeCK5+">多選框</option><option value='上傳框'"+inputFtypeCK6+">上傳框</option></select></td>"
                                        +"<td nowrap='nowrap'><div id='changetext"+j+"' style='display:"+displayText+"'><span style='color:#CCCCCC;font-weight:normal'>暫無</span></div><div id='changeselect"+j+"' style='display:"+displaySelect+"'><input type='text' name='inputFselect"+j+"' value='"+nextSelectVal+"' id='inputFselect"+j+"' size='20'/><span style='color:red;font-weight:normal'>*</span></div></td>"
                                        +"<td><input type='text' name='inputFdefault"+j+"' value='"+nextDefaultVal+"' id='inputFdefault"+j+"' size='10'/><span style='color:#CCCCCC;font-weight:normal'></span></td>"
                                        +"<td><input type='text' name='inputFtip"+j+"' value='"+nextTxtVal+"' id='inputFtip"+j+"'/></td>"
                                        +"<td nowrap='nowrap'><a href=\'#\' onclick=\'deltr("+j+")\'>刪除</a>&nbsp;&nbsp;<a href=\'#\' onclick=\'addnexttr("+j+")\'>下增</a>&nbsp;&nbsp;<a href=\'#\' onclick=\'addnexttr("+(j-1)+")\'>上增</a></td><td><a href=\'#\' onclick=\'moveup("+j+")\' id='moveup_"+j+"'>向上</a>&nbsp;&nbsp;<a id='movedown_"+j+"' href=\'#\' onclick=\'moveup("+(j+1)+")\'>向下</a></td>"
                                    +"</tr>");    
        
    }
    
    

    //刪除指定索引的<tr/>項
    deltr =function(index)
    {
        var _len = $(tablejquery+" tr").length;
        
        //刪除當前行
        $("tr[id='"+index+"']").remove();
        
        //new效果檢測
        var hasnewdotID = 0
        
        //當前刪除項的后面部分執行向上替換
        for(var i = index+1,j=_len;i<j;i++){
            //用於檢索並獲取之前的new效果項
            if(hasnewdotID==0) {
                hasnewdotID = $('#new_'+i)[0].style.display != 'none' ? i : 0;
            }
            
            //將當前行設置到上一行(當前行不保留)
            MoveTr(i,i-1);
                    
        }
        
         
    
        //如果檢索到哪個new效果項,設置到新的項去(新項為減1)    
        if(hasnewdotID != 0) {
            $('#new_'+(hasnewdotID-1)).show();
        }

        //設置服務器的獲取長度
          $('#inputlen').val($(tablejquery+" tr").length-1);
           //向上及向下的界限處理
           disableHref();
           
            return false;
    }
    

    //向上移動或向下移動
    moveup = function(index) {
        
        var _len = $(tablejquery+" tr").length;
        
        //有disableHref();  向上及向下的界限處理后,此下兩行可注釋,否則開啟
        //if(index==1) {alert('第一條無法向上');return false;}
        //if(index==_len)  {alert('最后條無法向下');return false;}
        
        
        //新增一行
        $(tablejquery).append("<tr id='"+_len+"' align='center'><td colspan='9'></td></tr>");

    
        //檢索之前的new效果
        var hasnewdotID = 0
        hasnewdotID = $('#new_'+index)[0].style.display != 'none' ? index : 0;
        if(hasnewdotID==0) {
            hasnewdotID = $('#new_'+(index-1))[0].style.display != 'none' ? (index-1) : 0;
        }
                
        //將當前行的內容設置到新增行,保留當前行
        MoveTr(index,_len,true);

         //將上行的內容設置到當前行,保留上行
         MoveTr(index-1,index,true);

         //將新增行內容設置到上行內容
         MoveTr(_len,index-1,true);
         
        

        //刪除新增行
        var tr=$("tr[id=\'"+_len+"\']")[0];
        var table=tr.parentNode;  
        table.removeChild(tr);
        
        //如果檢索到哪個new效果項,設置到新的項去
        if(hasnewdotID!=0) {
            if(hasnewdotID == index) {
                $('#new_'+(hasnewdotID-1)).show();
            }else{
                $('#new_'+index).show();
            }
        }
        
        //設置服務器的獲取長度
          $('#inputlen').val($(tablejquery+" tr").length-1);
           //向上及向下的界限處理
           disableHref();
           
            return false;
}

    //下增一行<tr/> 或上增一行
    addnexttr =function(index)
    {
        var _len = $(tablejquery+" tr").length;
         $('.newdot').hide();
        
        //新增一行
        $(tablejquery).append(newtrtemp(_len)); 

        //循環:從當前索引的 [下行的下行]到 [新增的項],行內容從循環當前項的"上行"獲得
        for(var i=_len,j=index+2; i>=j;i--)
        { 
            //將上行的內容設置到當前行並保留上行
              MoveTr(i-1,i,true);
        }   
    
         //還原新增行
         $("tr[id=\'"+(index+1)+"\']").replaceWith(newtrtemp(index + 1))
                    
        //新增行new效果
          $('#new_'+(index + 1)).show();

        //設置服務器的獲取長度
          $('#inputlen').val($(tablejquery+" tr").length-1);
           //向上及向下的界限處理
           disableHref();
           
            return false;
    }

    changeBH = function(ele) {
        var i = ele.name.toString().replace('inputFtype','');
        var v = ele.options[ele.selectedIndex].value ;
        if(v == '單選框' || v == '下拉框' || v == '多選框') {
            document.getElementById('changetext'+i).style.display = 'none';
            document.getElementById('changeselect'+i).style.display = '';
        }else{
            document.getElementById('changetext'+i).style.display = '';
            document.getElementById('changeselect'+i).style.display = 'none';
        }
    }

    

    })
   
    
    
</script>


然后就是可以省略只影響美觀不影響功能的CSS:

<!--樣式表全部刪除只會影響美觀,不會造成功能丟失-->
<style type="text/css">
    #tab td a:link {
            font-size:12px;
            color:#91A728;
            text-decoration:none;
        }
         
        #tab td a:visited {
            font-size:12px;
            color:#91A728;
            text-decoration:none;

        }
         
        #tab td a:hover {
            font-size:12px;
            color:#FF6600;
            text-decoration:none;
        }

         
        #tab td a:active {
            font-size:12px;
            color:#91A728;
            text-decoration:none;
        }
         

        .newdot {
            font-weight:bolder;
            font-family:'幼圓';
            margin-right:3px;
        }


        #tab {
            border-collapse:collapse;border:none;
        }
        #tab td {
            /*對所有被設置為position:relative的單元格會造成雙重邊,所以不應該在td上應該position:relative*/
            border: solid #76B0dF 1px;
            padding:3px;
        }
        #thead td {
        background-color:#079AE4;
        color:#FFFFFF;
        }

        .blocktip {
            display:block;
            color:#CCC;
            margin-top:10px;
        }
        
        #tbtoolbar {
            text-align:center;    
        }
        
        .btnclass{
            background-color:#079AE4;
            color:#FFF;
            border:2px solid #E9E7E7;
        }
</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM