各位老鸟,求帮助。一个很简单js,我想做一个按钮,它的背景颜色。点击奇数次为红色,偶数次为白色。
        <script type="text/javascript" >
        function change(btn) {
            var btn = document.getElementsByName("button");
            var times = 0;
            if (btn.onclicked) {
                times++;
                if (times % 2 == 0) {
                    btn.style.background = "red";
                }
                if (times % 2 == 1) {
                    btn.style.bac1ground = "white";
                }            }
        }
    </script>
</head>
<body>
<input type="button" value="点击试试" onclick="change(this)" />
</body>
</html>
这是我的代码,不知道哪里错了,还是怎么改。求帮助实现

解决方案 »

  1.   

    var btn = document.getElementsByName("button");
    这行删除
      

  2.   


    <html>
    <head>    <script type="text/javascript">
            var times = 0;
            function change(btn) {
                btn.style.background = times % 2 == 0 ? 'red' : 'white';
                times++;
            }
        </script></head>
    <body>
        <input name="button1" type="button" value="点击试试" onclick="change(this)" />
    </body>
    </html>
      

  3.   

    完整的代码
    <script type="text/javascript" >
      var times = 0;
      function change(btn) {  if (times % 2 == 0) {
      btn.style.background = "red";
      }
      if (times % 2 == 1) {
      btn.style.background = "white";
      }
      times++;
      }
      </script>
    </head>
    <body>
    <input type="button" value="点击试试" onclick="change(this)" />
    </body>
    </html>
      

  4.   

       你那times 应该放到定义函数上面,你放到函数里面每次点击都覆盖了
      4楼正解
     
      

  5.   

    哦 ,我知道了,应该是每次又重新复制为0了,每次自增都不起作用了。需要定义一个全局变量,你看是不是?所以var times=0应该放在最上面。谢谢老鸟哈,明白了。
      

  6.   

    首先将var times = 0;定义到函数外面再就是,var btn = document.getElementsByName("button"); 获得的是一个数组吧
     btn是个集合,若要使用,应该这样btn[0].style.background = "red";