开发者

How do I change an attribute in an HTML table's cell if I know the row and column index of the cell?

I know nothing about jQuery but am an experienced C++ programmer (not sure if that helps or hurts). I found jQuery code that gives me the row and column index of a cell in an HTML table when a user clicks on that cell. Using such row-column index numbers, I need to change an attribute's value in the previously selected cell and in the cell just clicked. The index numbers are produced and saved with this code:

var $trCurrent = 0; // Index of cell selected when page opens 
var $tdCurrent = 0; // i.e., previously selected cell

$(document).ready(function ()
{
    $("td").click(function ()
    {
        // How toclear previously selected cell's attribute here? ('class', 'recent')
        var oTr = $(this).parents("tr");
        $tdCurre开发者_StackOverflow中文版nt = oTr.children("td").index(this);

     });
    $("tr").click(function ()
    {
        $trCurrent = $(this)[0].rowIndex;
        // How to set new attributes here? ('class', 'current');
        // and continue work using information from currently selected cell

     });
});

Any help or hints would be appreciated. I do not even know if this is the way I should get the index of the row and column.


I would do this slightly different, if I understand your requirements. If when you click on a cell you need to do something to the previous clicked cell, use a class. So:

$("td").click(function() {
  $("td.active").removeClass("active");
  $(this).addClass("active");
});

So basically each time you click a cell, the previous active cell has its class removed and the new cell has it added. In the above code where I remove the class, you can do anything else you like to it and this avoids the problem of storing and referencing row/cell numbers.

If your goal is simply to style the cell differently, use that same class in your CSS eg:

td.active { background: yellow; }

When you render the page, you can make whichever cell you like active by giving it that class.

If you need to know the current and previous cells try this:

$("td").click(function() {
  $("td.active").removeClass("current").addClass("previous");
  $(this).addClass("current");
});

And then at any point you can do:

$("td.current")...
$("td.previous")...

If you really do need to know the row/cell number clicked try:

var rownum;
var cellnum;
$("td").click(function() {
  var row = $(this).closest("tr");
  rownum = $("tr").index(row);
  cellnum = row.children("td").index(this);
});

And if you need to reference that at any point:

$("tr:eq(" + rownum + ") > td:eq(" + cellnum + ")")...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜