gpt4 book ai didi

javascript - 在选择时更改 ,并在选择不同的 后恢复更改?

转载 作者:行者123 更新时间:2023-12-01 02:35:48 24 4
gpt4 key购买 nike

我正在构建一个表格,我希望更改所选单元格的背景颜色。然后,当我选择不同的单元格(并对这个新单元格应用相同的更改)时,我希望更改在第一个(不再选择)单元格中恢复。对此最好的方法是什么?这是我的代码:

var table = '';

for (var r = 0; r < rows; r++) {
table += '<tr>';

for (var c = 0; c < cols; c++) {
if (c == 0) {
if (r == 0) {
var cellID = r.toString();
cellID += letterArray[c - 1];
table += '<td style="min-width:50px; height:25px;">' + '</td>';
}
else {
var cellID = r.toString();
cellID += letterArray[c - 1];
table += '<td style="min-width:50px; height:25px">' + r + '</td>';
}
}
else if (r == 0 && c > 0) {
var cellID = r.toString();
cellID += letterArray[c - 1];
table += '<td style="min-width:50px; height:25px">' + letterArray[c - 1] + '</td>';
}
else {
var cellID = r.toString();
cellID += letterArray[c - 1];
table += '<td id="' + cellID + '" style="min-width:50px; height:25px;" onclick="selectCell(this)">' + '</td>';
}
}
table += '</tr>';
}

将表格写入文档:

document.write('<table id="table" border=1>' + table + '</table>');

选择单元格函数:

function selectCell(x) {
alert("Row = " + x.parentNode.rowIndex + " Col = " + String.fromCharCode((x.cellIndex - 1) + 65));
x.style.backgroundColor = 'purple';
}

这就是我遇到问题的地方。当我单击第一个单元格时,我的警报会显示我选择的单元格的信息,然后更改背景颜色。然后,当我选择不同的单元格时,它会用新的单元格行和列信息提醒我,并更改颜色。

恢复先前选定单元格颜色变化的最佳方法是什么?

感谢您的时间和精力!

最佳答案

您应该创建一个应用背景颜色的 CSS 类,并在您的函数中添加/删除它。您的函数可以检查已经具有该类的元素,如下所示:

CSS:

.selected {
background-color: purple;
}

JS:

function selectCell(x) {
var currentSelection = document.querySelector('.selected');

if (currentSelection) {
currentSelection.classList.remove('selected');
}

x.classList.add('selected');
}

关于javascript - 在选择时更改 <td>,并在选择不同的 <td> 后恢复更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47931026/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com