我想点击相应的链接改变背景,为什么点击哪个链接都是黑色的
<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>

解决方案 »

  1.   

    测试一下你之前的
                    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);
            }
          }
      

  2.   

    闭包问题  看看 http://blog.csdn.net/xiaofan_sap/archive/2009/11/05/4772625.aspx
      

  3.   


    for(x in colors){
           background(colors[x]);

    点击每一个链接的时候,你都给中间的粉色方块附了四次颜色值,最后一个是黑的。所以,就显示黑色了。你把color[4]去掉看看,肯定变成点哪个链接都是红色
      

  4.   

    测试一下你之前的                for(x in colors){
                        alert(x)  //写掉了
                        background(colors[x]);
                    }