OnClick将用户重定向到另一个URL

时间:2017-11-29 19:25:21

标签: javascript html css anchor

我想按此顺序更改bg颜色:[黑色,白色,红色,绿色,蓝色]

<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 个答案:

答案 0 :(得分:0)

你必须这样做

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

从html中删除;

 <div class="test" onclick="test()">Click me!!</div>

答案 1 :(得分:-1)

您的代码无效的原因是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>