我对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
});
});
任何帮助或提示将不胜感激。我甚至不知道这是否应该得到行和列的索引。
答案 0 :(得分:5)
如果我理解你的要求,我会做的略有不同。如果单击单元格时需要对上一个单击的单元格执行某些操作,请使用类。所以:
$("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 + ")")...