【问题标题】:How do I change an attribute in an HTML table's cell if I know the row and column index of the cell?如果我知道单元格的行和列索引,如何更改 HTML 表格单元格中的属性?
【发布时间】:2011-02-04 02:54:35
【问题描述】:

我对 jQuery 一无所知,但我是一位经验丰富的 C++ 程序员(不确定这是否有帮助或有伤害)。我找到了 jQuery 代码,当用户单击该单元格时,该代码为我提供了 HTML 表格中单元格的行和列索引。使用这样的行列索引号,我需要更改先前选择的单元格和刚刚单击的单元格中的属性值。使用以下代码生成并保存索引号:

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");
        $tdCurrent = 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

     });
});

任何帮助或提示将不胜感激。我什至不知道这是否是我应该获取行和列索引的方式。

【问题讨论】:

    标签: jquery html css html-table jquery-selectors


    【解决方案1】:

    如果我了解您的要求,我会做的略有不同。如果单击单元格时需要对上一个单击的单元格执行某些操作,请使用类。所以:

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

    所以基本上每次单击一个单元格时,前一个active 单元格都会删除其类,并添加新单元格。在上面我删除类的代码中,你可以对它做任何你喜欢的事情,这避免了存储和引用行/单元格编号的问题。

    如果您的目标只是为单元格设置不同的样式,请在 CSS 中使用相同的类,例如:

    td.active { background: yellow; }
    

    当你渲染页面时,你可以通过给它那个类来激活你喜欢的单元格。

    如果您需要知道当前和以前的单元格,请尝试以下操作:

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

    然后你可以在任何时候做:

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

    如果您确实需要知道单击的行/单元格编号,请尝试:

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

    如果您需要在任何时候引用它:

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

    【讨论】:

    • @cletus,我觉得你很棒
    • Cletus,太棒了(而且非常简单)。谢谢!
    猜你喜欢
    • 2013-12-01
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    相关资源
    最近更新 更多