如何在添加自定义列时为每个单元格提供唯一id

How to give a unique id for each cell when adding custom columns?

本文关键字:单元格 id 唯一 添加 自定义      更新时间:2023-09-26

我编写了以下代码来向我的表添加一个自定义列。但我想为这些列中的每个单元格添加一个唯一的id。格式应该是(列号)(单元格号>)例如:-对于第4列:- a41, a42, a43, ........有人能告诉我怎么做吗。谢谢你!

$(document).ready(function () 
{
     var myform = $('#myform'),
         iter = 4;
     $('#btnAddCol').click(function () {
         myform.find('tr').each(function(){
           var trow = $(this);
           var colName = $("#txtText").val();
           if (colName!="")
           {
             if(trow.index() === 0){
                 //trow.append('<td>'+iter+'</td>');
                 $(this).find('td').eq(5).after('<td>'+colName+iter+'</td>');
             }else{
                 //trow.append('<td><input type="text" name="al'+iter+'"/></td>');
                 $(this).find('td').eq(5).after('<td><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
             }
            } 
         });
         iter += 1;
     });
 });

您似乎有代码修改表的内容(添加单元格),这相当强烈地反对将id添加到每个单元格,或至少一个基于其行/列位置,因为您必须更改他们当您添加单元格到表。

但是如果你真的想这样做,在你的修改之后,运行一个嵌套循环,并使用传递到each的索引分配id,覆盖他们可能拥有的任何以前的id:

myform.find("tr").each(function(row) {
    $(this).find("td").each(function(col) {
        this.id = "a" + row + col;
    });
});

(注意这里假定没有嵌套表)

try this

if(trow.index() === 0){
   //trow.append('<td>'+iter+'</td>');
   $(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'">'+colName+iter+'</td>');
}else{
   //trow.append('<td><input type="text" name="al'+iter+'"/></td>');
   $(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'"><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}

你只需要定义并迭代column_no和cell_no变量

当所有其他单元格的编号一致时(例如使用值为rXcX的data-attribute),您可以使用如下内容:

function addColumn(){
   $('table tr').each( 
          function(i, row) {
              var nwcell = $('<td>'), previdx;
              $(row).append(nwcell);
              previdx = nwcell.prev('td').attr('data-cellindex');
              nwcell.attr('data-cellindex',
                          previdx.substr(0,previdx.indexOf('c')+1)
                          + (+previdx.substr(-previdx.indexOf('c'))+1));
          });
}

在this jsFiddle