我的目标是更改表中列的背景颜色,而不是按ID或名称单独寻址每个数据条目.我知道有几种方法可以做到这一点,我已经尝试过3个确切的方法,而且每个方法都有问题.为了简单和清晰起见,在这个问题中,我问如何使用DOM中的element.style.backgroundColor对象成功地完成它.这是我的HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="tester.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript" src="tester.js"></script>
</head>
<body>
<button type="button" onClick="testerFunction()">Test</button>
<table>
<tr>
<th class="col1">Column 1 Header</th>
<th class="col2">Column 2 Header</th>
</tr>
<tr>
<td class="col1">R1 C1</td>
<td class="col2">R1 C2</td>
</tr>
<tr>
<td class="col1">R2 C1</td>
<td class="col2">R2 C2</td>
</tr>
</table>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我的CSS文件:
.col1{
background-color:lime;
}
Run Code Online (Sandbox Code Playgroud)
和我的Javascript文件:
function testerFunction() {
alert (document.getElementsByClassName('.col1').style.backgroundColor);
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我在IE,Firefox和Chrome中得到大致相同的错误:
无法读取Undefined属性'backgroundColor'.
我觉得它与document.getElementsByClassName DOM对象返回的数据类型有关.引用的网站说它返回一个HTMLcollection.我发现的其他地方说它返回了元素的"列表".我尝试制作一个数组并将结果分配给数组并使用循环访问数组中的每个元素,但在同一个地方得到了相同的错误.可能是因为我不知道如何处理"集合".无论如何,我期待,"石灰"或十六进制或rgb等价,因为这是我在CSS文件中定义的.我希望能够用Javascript更改它.任何帮助将非常感激.谢谢!
编辑:为Shylo Hana的答案添加了参数,使其更加模块化
function testerFunction() {
changeColumnColor('col1','blue');
}
function changeColumnColor(column,color) {
var cols = …
Run Code Online (Sandbox Code Playgroud) 我花了大约12个小时查看这段代码,并摆弄它,试图找出有递归问题的地方,因为我得到了"超出最大调用堆栈大小"错误,并且没有找到它.比我聪明的人请帮助我!
到目前为止,我发现的只是当我创建对象时spot
,一个circle
对象,问题就消失了,但是当我把它变成'pip'时,我得到了这个堆栈溢出错误.我用一个friggin'显微镜看了一下pip类,但仍然不知道为什么会发生这种情况!
var canvas = document.getElementById('myCanvas');
//-------------------------------------------------------------------------------------
// Classes
//-------------------------------------------------------------------------------------
//=====================================================================================
//CLASS - point
function point(x,y){
this.x = x;
this.y = y;
}
//=====================================================================================
// CLASS - drawableItem
function drawableItem() {
var size = 0;
this.center = new point(0,0);
this.lineWidth = 1;
this.dependentDrawableItems = new Array();
}
//returns the size
drawableItem.prototype.getSize = function getSize(){
return this.size;
}
// changes the size of this item and the relative size of all dependents
drawableItem.prototype.changeSize = function(newSize){
var relativeItemSizes …
Run Code Online (Sandbox Code Playgroud)