代码之家  ›  专栏  ›  技术社区  ›  Suppy

OnClick将用户重定向到另一个url[关闭]

  •  -3
  • Suppy  · 技术社区  · 7 年前

    我想按以下顺序更改背景颜色:[黑,白,红,绿,蓝]

    <body style="background-color:black">
    
        <script type="text/javascript">
            function test() {
                var bg = document.bgColor;
                var e = document.getElementById("tests");
    
                if (bg == "black")  {e.style.backgroundColor = "white";}
                else if (bg == "white") {e.style.backgroundColor = "red";}
                else if (bg == "red") {e.style.backgroundColor = "green";}
                else if (bg == "green") {e.style.backgroundColor = "blue";}
                else if (bg == "blue") {"<a href="/testson"/>";}
                            }
    
        </script>
        <div class="test"; onclick="test()"></div>
    </body>
    

    但当我点击页面上的某个地方时,什么都没发生。

    2 回复  |  直到 7 年前
        1
  •  0
  •   Pranay Rana    7 年前

    你必须这样做

     // similar behavior as clicking on a link
    window.location.href = "http://stackoverflow.com";
    

    去除 ; 从html

     <div class="test" onclick="test()">Click me!!</div>
    
        2
  •  -1
  •   Marcello B.    7 年前

    代码不起作用的原因是div标记不支持该操作 onclick . 为了使div可点击,您需要为div设置一个ID,然后在javascript中分配一个事件处理程序来处理点击,例如:

    <head>
        <script type="text/javascript">
            function test() {
                var bg = document.bgColor;
                var e = document.getElementById("tests");
    
                if (bg == "black")  {
                    e.style.backgroundColor = "white";
                }
                else if (bg == "white") {
                    e.style.backgroundColor = "red";
                }
                else if (bg == "red") {
                    e.style.backgroundColor = "green";
                }
                else if (bg == "green") {
                    e.style.backgroundColor = "blue";
                }
                else if (bg == "blue") {
                    "<a href="/testson"/>";
                }
            }
            function AddHandlers(){
                var something = document.getElementById('someid');
    
                something.style.cursor = 'pointer';
                something.onclick = function() {
                     test();
                };
            }
        </script>
    </head>
    
    <body onload="AddHandlers()">
        <div class="test" id="someid">Click me!!</div>
    </body>