最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamic HTML row - add id on TR - Stack Overflow

programmeradmin5浏览0评论

How to add an ID (value 1, 2, 3, etc.) on each new I have now so that my script creates a new row, but would need an ID to each

FIDDLE

CODE:

function deleteRow(tableID) {
    try {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;
        for(var i=0; i<rowCount; i++) {
            var row = table.rows[i];
            var chkbox = row.cells[0].childNodes[0];
            if(null != chkbox && true == chkbox.checked) {
                if(rowCount <= 1) {
                    alert("Cant delete all rows");
                    break;
                }
                table.deleteRow(i);
                rowCount--;
                i--;
            }
        }
    }catch(e) {
        alert(e);
    }
}

How to add an ID (value 1, 2, 3, etc.) on each new I have now so that my script creates a new row, but would need an ID to each

FIDDLE

CODE:

function deleteRow(tableID) {
    try {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;
        for(var i=0; i<rowCount; i++) {
            var row = table.rows[i];
            var chkbox = row.cells[0].childNodes[0];
            if(null != chkbox && true == chkbox.checked) {
                if(rowCount <= 1) {
                    alert("Cant delete all rows");
                    break;
                }
                table.deleteRow(i);
                rowCount--;
                i--;
            }
        }
    }catch(e) {
        alert(e);
    }
}
Share Improve this question edited Jan 1, 2017 at 19:00 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Feb 4, 2015 at 9:06 Lars HolmqvistLars Holmqvist 811 gold badge2 silver badges10 bronze badges 2
  • Something like this updated fiddle? jsfiddle/pkz1vszu/1 – Nicolae Olariu Commented Feb 4, 2015 at 9:14
  • I posted an answer below, but... why you need to add IDs when adding/removing rows works without that? Do you really need ID attribute there? – pavel Commented Feb 4, 2015 at 9:26
Add a ment  | 

2 Answers 2

Reset to default 4

So, simply add id when you create new line. Removed IDs aren't used again, ID is still unique.

var row_id = 1;

function addRow(tableID) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    row.id = 'id' + row_id; // ID is 'id#' because valid ID can't start with a number
    row_id++;
    ...

http://jsfiddle/pkz1vszu/2/

You can use jQuery to make it easier:

<head>
    <script src="js/jquery-1.11.1.min.js"></script>
</head>
<body>
   <script>
   $("#create_button").click(function(){
      $("<tr>").attr({"id":"id_"+number}).appendTo("#table");
   ]);
   </script>
   ...
   ...
</body>

发布评论

评论列表(0)

  1. 暂无评论