使用唯一ID添加/删除行到表

时间:2012-08-24 15:10:34

标签: javascript

这是我的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创建..我需要稍后将值保存到数据库

2 个答案:

答案 0 :(得分: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); 
    };
}());

答案 1 :(得分:0)

你也可以使用jquery来获取最后一个id(假设你的行按升序分配id),然后根据它增加

 var highestId = parseInt($("tr:last").attr("id"));
 clone.id = ++highestId ;