javascript 如何动态更改表格单元格文本颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13265899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change dynamically tabe cell text colors?
提问by Thomas
I need a solution to change dynamically via javascript the text color of table cells. The text can be the following colors: blue, green, red and black.
我需要一个解决方案来通过 javascript 动态更改表格单元格的文本颜色。文本可以是以下颜色:蓝色、绿色、红色和黑色。
Table example:
表示例:
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset="UTF-8">
<script src="jquery-mobile/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery.mobile-1.0.min.js" type="text/javascript"></script>
</head>
<body>
<div data-role="page" id="page">
<div data-role="content">
<table width="100%" border="0" id="friends" class="menu">
<tr id="friend1">
<td>First name</td>
<td>Surname</td>
</tr>
<tr id="friend2">
<td>First name</td>
<td>Surname</td>
</tr>
<tr id="friend3">
<td>First name</td>
<td>Surname</td>
</tr>
<tr id="friend4">
<td>First name</td>
<td>Surname</td>
</tr>
<tr id="friend5">
<td>First name</td>
<td>Surname</td>
</tr>
</table>
</div>
</div>
</body>
</html>
How can I change the text color? Conditions are, that I could do this dynamically via javascript and more than one time. That means I need to set a color (e.g. red), later reset the color to black and set it following to another color (e.g. blue).
如何更改文本颜色?条件是,我可以通过 javascript 并且不止一次地动态执行此操作。这意味着我需要设置一种颜色(例如红色),稍后将颜色重置为黑色并将其设置为另一种颜色(例如蓝色)。
I saw some examples with setting the color via id, but I found no way to transfer this example to table cells and each cell could have different colors.
我看到了一些通过 id 设置颜色的例子,但我发现没有办法将这个例子转移到表格单元格,每个单元格可以有不同的颜色。
Can someone help me?
有人能帮我吗?
回答by Mic
you can go through all td's
你可以通过所有的td
var tds = document.getElementsByTagName("td");
for(var i = 0, j = tds.length; i < j; ++i)
tds[i].style.color = "#00AA00";
OR
或者
you can go through td's that are childs of a special element:
您可以查看作为特殊元素的子项的 td:
var myNode = document.getElementById("friend2");
var tds = myNode.getElementsByTagName("td");
for(var i = 0, j = tds.length; i < j; ++i)
tds[i].style.color = "#00AA00";
greetings!
问候!
回答by Th0rndike
create a class for each color in your css file:
为 css 文件中的每种颜色创建一个类:
.redCell{
color:red;
}
.blueCell{
color:blue;
}
.yellowCell...
then, add the class to the TD you need:
然后,将类添加到您需要的 TD:
$('#friend01').addClass('blueCell');
if you need to remove the color:
如果您需要去除颜色:
$('#friend01').removeClass('blueCell');
if you need to know if a cell has a certain color:
如果您需要知道单元格是否具有某种颜色:
$('#friend01').hasClass('blueCell');