0

我需要为我的表格单元格分配数字,这些数字从一个单元格到另一个单元格递增。我尝试了一个forloop,但是在每次循环之后将递增的计数器分配给单元格的标题时遇到了麻烦。我有这个代码 -

$(function(){
var row = $('#seat_map tr:last td.freeSeat')
for(i=0; i<row.length; i++){
        row.attr('title', i);   
    }
});

此代码仅在循环完成后将 i 的最终值分配给所有单元格的标题...而不是将 '1、2、3' 等分配给标题。我也许应该补充一点,该表也是使用 jquery 动态生成的。为模糊的标题和描述道歉 - 我尽力了!

谢谢

4

4 回答 4

1

Use .each() function of jquery

The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

jQuery:

$('#seat_map tr:last td.freeSeat').each(function(index){
    $(this).attr('title', index+1)
})

DEMO

于 2013-02-20T10:49:58.270 回答
1

好吧,.each()无论如何你都可以使用

var row = $('#seat_map tr:last td.freeSeat');
$.each(row, function(index){
    $(this).attr('title', index+1);
});

但实际上,您可以直接从选择器中执行此操作。

$('#seat_map tr:last td.freeSeat').each(function(index) {
    $(this).attr('title', index+1);
});
于 2013-02-20T10:42:40.393 回答
1

“此代码仅在循环完成后将 i 的最终值分配给所有单元格的标题”

这是因为在每次迭代中,您都在设置每个匹配元素的属性。(对jQuery 对象row.attr('title',i)中的每个元素进行操作。)row

如果您使用 jQuery,您会发现使用它的.each()方法比使用传统for循环更简单:

$(function(){
    var rows = $('#seat_map tr:last td.freeSeat');
    rows.each(function(i) {
       $(this).attr('title',i);
    });
});

除非您稍后将其用于其他用途,否则您根本不需要该rows变量:

$(function(){
    $('#seat_map tr:last td.freeSeat').each(function(i) {
       $(this).attr('title',i);
    });
});

但是要使用for循环来执行此操作,您可以使用该eq()方法来访问当前项目:

$(function(){
    var row = $('#seat_map tr:last td.freeSeat')
    for(i=0; i<row.length; i++){
        row.eq(i).attr('title', i);   
    }
});

i这些方法中的任何一个都将以at开头0,因此i+1如果您希望显示的编号以 开头,请使用1

于 2013-02-20T10:43:04.027 回答
0

Try this:

$(function(){
   var row = $(document).children('#seat_map tr:last').find('td.freeSeat');
   for(i=0; i<row.length; i++){
      row.attr('title', i);   
   }
});

or this:

$(function(){
   var row = $('#seat_map tr:last td.freeSeat', this);
   for(i=0; i<row.length; i++){
      row.attr('title', i);   
   }
});

As you mentioned I should perhaps add that the table is dynamically generated using jquery

于 2013-02-20T10:49:51.633 回答