我在第Uncaught TypeError: Cannot read property 'style' of null
行收到错误document.getElementById(blueChild).style.border = "2px solid white"
,我看上去并没有找到解决方案。这是我的代码:
var scroller = function(direction, team){
console.log("scrolling")
if (team == "blue"){
if (direction == "left"){
blueCount = blueCount - 1
}
if (blueCount < 0){
blueCount = 3
}
if (redCount < 0){
redCount = 3
}
var blueChildren = document.getElementById('blueSelector').getElementsByTagName('div')
var blueChild = blueChildren[blueCount]
document.getElementById(blueChild).style.border = "2px solid white"
for (var i = 0; i < blueChildren.length; i++){
if (i !== blueCount){
blueChild = blueChildren[i]
document.getElementById(blueChild).style.border = "2px solid black"
}
}
}
}
scroller("left", "blue")
顺便说一下,blueCount
,redCount
的全局默认值为0
多请求HTML
<html>
<head>
<link rel="stylesheet" href="normalize.css">
<link rel="stylesheet" href="main.css">
<script src="jquery.js"></script>
<script src="rectangle.js"></script>
<script src="main.js"></script>
</head>
<body>
<canvas id="canvas">You're browser does not support the canvas tag. Go and get a real browser, nub</canvas>
<div id="redSelector">
<div class="genericButton" id="zombieRed">Zombie</div>
<div class="genericButton" id="skeletonRed">Skeleton</div>
<div class="genericButton" id="creeperRed">Creeper</div>
<div class="genericButton" id="spideBlue">Spider</div>
</div>
<div id="blueSelector">
<div class="genericButton" id="zombieBlue">Zombie</div>
<div class="genericButton" id="skeletonBlue">Skeleton</div>
<div class="genericButton" id="creeperBlue">Creeper</div>
<div class="genericButton" id="spiderBlue">Spider</div>
</div>
</body>
我想要实现的目标是评估blueSelector
的子元素,并使其中一个带有白色边框,并带有黑色边框。
答案 0 :(得分:2)
你只需要这样做:
blueChild.style.border = "2px solid white"
和
blueChild.style.border = "2px solid black"
因为您创建的blueChild
变量指向HTML元素,而不是表示ID的String。
编辑:哦,你忘记了一句话:
here
↓
scroller("left", "blue")
答案 1 :(得分:0)
我找到了解决方案!事实证明我使用blueCount
定义var blueCount
,当我在blueChildren
数组中使用变量作为索引时,blueCount
为undefined
和{{1}然后是未定义的。
希望人们从我的愚蠢错误中学习xD