我想点击相应的链接改变背景,为什么点击哪个链接都是黑色的
<html>
<head>
<title>我的主页</title>
<style type="text/css">
*{font-size:13px;}
ul{
list-style:none;
}
#colorss{
width:100px;
height:110px;
border:1px solid #ccc;
margin:0 auto;
background:pink;
text-align:center;
line-height:110px;
}
</style>
</head>
<body>
<ul id="menu">
<li><a href="#">黄色</a></li>
<li><a href="#">蓝色</a></li>
<li><a href="#">绿色</a></li>
<li><a href="#">红色</a></li>
<li><a href="#">黑色</a></li>
</ul>
<div id="colorss">
默认粉色
</div>
<script type="text/javascript">
function background(colorsss){
var colorss = document.getElementById("colorss")
colorss.style.backgroundColor = colorsss;
}
function click(){
var list = document.getElementById("menu");
var links = list.getElementsByTagName("a");
for(var i=0; i<links.length; i++){
links[i].onclick = function(){
var x;
var colors = new Array();
colors[0] = "yellow";
colors[1] = "blue";
colors[2] = "green";
colors[3] = "red";
colors[4] = "black";
for(x in colors){
background(colors[x]);
}
}
}
}
click();
</script>
</body>
</html>
<html>
<head>
<title>我的主页</title>
<style type="text/css">
*{font-size:13px;}
ul{
list-style:none;
}
#colorss{
width:100px;
height:110px;
border:1px solid #ccc;
margin:0 auto;
background:pink;
text-align:center;
line-height:110px;
}
</style>
</head>
<body>
<ul id="menu">
<li><a href="#">黄色</a></li>
<li><a href="#">蓝色</a></li>
<li><a href="#">绿色</a></li>
<li><a href="#">红色</a></li>
<li><a href="#">黑色</a></li>
</ul>
<div id="colorss">
默认粉色
</div>
<script type="text/javascript">
function background(colorsss){
var colorss = document.getElementById("colorss")
colorss.style.backgroundColor = colorsss;
}
function click(){
var list = document.getElementById("menu");
var links = list.getElementsByTagName("a");
for(var i=0; i<links.length; i++){
links[i].onclick = function(){
var x;
var colors = new Array();
colors[0] = "yellow";
colors[1] = "blue";
colors[2] = "green";
colors[3] = "red";
colors[4] = "black";
for(x in colors){
background(colors[x]);
}
}
}
}
click();
</script>
</body>
</html>
for(x in colors){
background(colors[x]);
} function click(){
var list = document.getElementById("menu");
var links = list.getElementsByTagName("a");
for(var i=0; i<links.length; i++){
links[i].onclick = function(i){
return function(){
var colors = new Array();
colors[0] = "yellow";
colors[1] = "blue";
colors[2] = "green";
colors[3] = "red";
colors[4] = "black";
background(colors[i])
}
}(i);
}
}
for(x in colors){
background(colors[x]);
}
点击每一个链接的时候,你都给中间的粉色方块附了四次颜色值,最后一个是黑的。所以,就显示黑色了。你把color[4]去掉看看,肯定变成点哪个链接都是红色
alert(x) //写掉了
background(colors[x]);
}