我对 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");
});
所以基本上,每次您单击一个单元格时,前一个事件
单元格的类都会被删除,而新单元格则会添加它。在上面我删除该类的代码中,您可以对其执行任何您喜欢的操作,这可以避免存储和引用行/单元格编号的问题。
如果您的目标只是以不同的方式设置单元格样式,请在 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 + ")")...
关于jquery - 如果我知道单元格的行索引和列索引,如何更改 HTML 表格单元格中的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2573268/