当用javascript克隆一行表时,我需要内部元素的id和名称

时间:2013-11-29 18:45:03

标签: javascript html

点击 areasensornewline_button 时,会创建一个新行并将其附加到表格中。我可以更改行ID,但此行中的所有新下拉框现在都有 id =“selectedArea0” id =“selectedSensor0” name =“AreaBinding0” name =“sensorBinding0”。这些必须是1,2和堡垒。任何帮助将不胜感激!!!!

    <table border="0" id="areasensor_table">
        <tr id="areasensor_row0">
            <td id="area_column0">
                <select name="areaBinding0" id="selectedArea0"> @for(area <- areas) {
                    <option value="@area.uniqueid">@area.name</option>}
                </select>
            </td>
            <td id="sensor_column0">
                <select name="sensorBinding0" id="selectedSensor0"> @for(sensor <- sensors) {
                    <option value="@sensor.id">@sensor.name</option> } 
                </select>
            </td>
            <td>
                <a class="glyphicon glyphicon-plus" id="areasensornewline_button"></a>
            </td>
        </tr>
    </table>
    <p>
    <p>
<script>
var q = 1;
document.getElementById('areasensornewline_button').onclick = cloneRowAreaSensor;

function cloneRowAreaSensor() {
    var row = document.getElementById('areasensor_row0'); // find row to copy
    var table = document.getElementById('areasensor_table'); // find table to append to
    var clone = row.cloneNode(true); // copy children too
    var innerClone = row.innerHTML;
    clone.id = 'areasensor_row' + q; // change id or other attributes/contents
    q++;
    table.appendChild(clone); // add new row to end of table
}
</script>

2 个答案:

答案 0 :(得分:1)

一个技巧是使用正则表达式,但远非完美......

        function cloneRowAreaSensor() {
            var row = document.getElementById('areasensor_row0'); // find row to copy
            var table = document.getElementById('areasensor_table'); // find table to append to
            var clone = row.cloneNode(true); // copy children too
            clone.innerHTML = clone.innerHTML.replace(/0"/g, q + '"');
            clone.id = 'areasensor_row' + q; // change id or other attributes/contents
            q++;
            table.appendChild(clone); // add new row to end of table
        }

添加的行放在tbody html标记之外。你真的应该使用jQuery,il会帮助你很多。

答案 1 :(得分:0)

您的代码仅适用于第一次。创建一个计数器,用它来命名元素。

示例:

var count = 1;
for(i = 0; i<= 10; i++){
var row = document.getElementById('areasensor_row'+ count +'');
}

这是一个简单的例子。您需要重新构建代码,如此示例。 (这个cicle不是更好的例子,但它适用于10个元素)