1

这是我的 javascript 复制行和删除行

function cloneRow()
 {
         var row = document.getElementById("r1"); 
         var table = document.getElementById("t1"); 
         var clone = row.cloneNode(true); 
         clone.id = "newID";
         table.appendChild(clone); 
 }
 function removeRowFromTable()
 {
 var tbl = document.getElementById('div1');
 var lastRow = tbl.rows.length;
 if (lastRow > 1) tbl.deleteRow(lastRow - 1);
 }

这是我的桌子:

 <table id="div1" style="display:none">
    <tbody id="t1">
    <tr id="r1"><td>
<form:input path="hostname" value="hostname" onfocus="if(this.value == 'hostname'){this.value =''}" onblur="if(this.value == ''){this.value ='hostname'}" size="30" maxlength="30"/>
<form:input path="directory" value="directory" onfocus="if(this.value == 'directory'){this.value =''}" onblur="if(this.value == ''){this.value ='directory'}" size="15" maxlength="15"/>
<form:input path="username" value="username" onfocus="if(this.value == 'username'){this.value =''}" onblur="if(this.value == ''){this.value ='username'}" size="15" maxlength="15"/>
<form:input path="password" value="password" onfocus="if(this.value == 'password'){this.value =''}" onblur="if(this.value == ''){this.value ='password'}" size="15" maxlength="15"/></td></tr>
    </tbody>
<input type="button" onclick="cloneRow()" value="+" />
<input type="button" onclick="removeRowFromTable();" value="-" />
    </table>

代码正在动态添加或删除行..但是,我怎么知道它们是使用唯一 ID 创建的..我需要稍后将值保存到数据库

4

2 回答 2

2

使用带有局部变量的闭包:

var cloneRow = (function()
{
    var id_num = 0;

    return function ()
    {
        var row = document.getElementById("r1"); 
        var table = document.getElementById("t1"); 
        var clone = row.cloneNode(true); 

        clone.id = "newID" + id_num++;
        table.appendChild(clone); 
    };
}());
于 2012-08-24T15:15:06.233 回答
0

您还可以使用 jquery 来获取最后一个 id(前提是您的行按升序分配了 id),然后根据该值递增

 var highestId = parseInt($("tr:last").attr("id"));
 clone.id = ++highestId ;
于 2012-08-24T15:27:33.930 回答