-1

我有一个使用淘汰赛 js 动态创建的表,如下所示:

我的问题是为新创建的列动态分配一个 id。我需要遍历最后一列。

<table>
    <tr data-bind="foreach: activeColumns">
        <th data-bind="text: display"></th>
    </tr>
    <tbody id="sortable" data-bind="foreach: rows">
        <tr data-bind="foreach: $root.activeColumns">
            <td id="uniquename">
                <span  data-bind="visible: readonly, text: $parent[property]"></span>
                <input data-bind="visible: !readonly, value: $parent[property]"/>
            </td>
        </tr>
    </tbody>
</table>
4

1 回答 1

2

You don't need to iterate through tr elements for selecting the last one, you can use :last selector or last method:

$('#sortable tr').last(); // last tr element  
$('#sortable td').last(); // last td element

In case that you want to change attributes of last tr's td elements, you can use each method:

$('#sortable tr').last().children().each(function(index){
   // $(this).attr('id', 'wildguess' + index)
})  

Or attr method:

$('#sortable tr').last().children().attr('id', function(index){
   return 'wildguess' + ++index // unique IDs bases on the index
})  

My problem is to dynamically assign an id for the newly created columns.

However best solution is generating unique IDs at first.

于 2012-12-26T13:13:29.300 回答