繁体   English   中英

如果知道单元格的行和列索引,如何更改HTML表单元格中的属性?

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

我对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

     });
});

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

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

$("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 + ")")...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM