gpt4 book ai didi

javascript - 如何使用javascript更改html表格中列的颜色

转载 作者:行者123 更新时间:2023-12-03 10:03:53 24 4
gpt4 key购买 nike

window.onload = function () {
var tbl = document.getElementById('tbl');
var tr = tbl.getElementsByTagName('tr');
for (var i = 0; i < tr.length; i++) {
var first_td = tr[i].getElementsByTagName('td')[0];
first_td.onmouseover = function () {
hover('on');
}
first_td.onmouseout = function () {
hover('off');
}
}
function hover(state) {
for (var i = 0; i < tr.length; i++) {
var first_td = tr[i].getElementsByTagName('td')[0];
if (state == 'on') {
first_td.style.color = 'White';
first_td.style.background = 'RED';
}
else if (state == 'off') {
first_td.style.color = '#000';
first_td.style.background = '#fff';
}
}
}
}

我这样做了,但此代码不适用于所有表列。在此代码中,只有任何一列起作用。其他列不起作用。请提供更改所有列在悬停时更改颜色的代码。

最佳答案

您明确仅采用第一列元素。将您的脚本替换为

var tbl = document.getElementById('tbl');

var tr = tbl.getElementsByTagName('tr');
for (var i = 0; i < tr.length; i++) {
var tdlist=tr[i].getElementsByTagName('td');
for(var j=0; j<tdlist.length; j++)
{
var first_td = tdlist[j];
first_td.onmouseover = function () {
hover(this,'on');
}
first_td.onmouseout = function () {
hover(this,'off');
}
}
}
function hover(obj,state) {
for (var i = 0; i < tr.length; i++) {
var first_td = tr[i].getElementsByTagName('td')[obj.cellIndex];
if (state == 'on') {
first_td.style.color = 'White';
first_td.style.background = 'RED';
}
else if (state == 'off') {
first_td.style.color = '#000';
first_td.style.background = '#fff';
}
}
}

关于javascript - 如何使用javascript更改html表格中列的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30455528/

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