开发者

jQuery select last cell in a table by condition

I have two tables. The first is one row high and contains 7 tds.

The second is 6 rows high and contains 7 tds.

When a user clicks a td in the first table, the last cell in table 2 in the corresponding column that has class 'x', has class 'x' removed and class 'y' added.

So next time when the same column is clicked, the cell above it would have class 'x' removed and class 'y' added, and so on...

I have managed to select the corresponding column using a plugin that allows you to select 'nth-col':

$('#table1 td').clic开发者_如何学JAVAk(function(){

    var col = ($(this).index()+1);

    $('#table2 td:nth-col('+col+')').removeClass('x').addClass('y');

});

But just cant figure out how to select the row!

If you are wondering what I'm going on about then basically I'm trying to make connect four.


You can do it without any plugins. Go through the rows in reverse order, check the Nth td element. Exit from the loop after the first one you've found. This is a simple solution, might not be properly optimised to handle thousands of rows/columns though. :)

Live demo: http://jsfiddle.net/yydZ3/1/

//Set all classes to x
$('td').addClass('x');

$('td').click(function(){
    var $this = $(this);
    var col = $this.index();

    //Iterate through rows in reverse order
    $($('tr').get().reverse()).each(function(){
        var $cell = $(this).find('td:eq('+col+')');
        if($cell.hasClass('x')){
            //Found one, this must be the last in this column
            $cell.removeClass('x').addClass('y');

            //Exit out of each loop
            return false;
        }
    });
});


Select the adequate tr (row), then the td element (cell):

$('#table2 tr:eq('+row+') td:eq('+col+')').removeClass('x').addClass('y');

See a very basic test: http://jsfiddle.net/MgTGf/1/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜