如何为链接指定随机颜色?

时间:2012-04-15 16:21:02

标签: javascript

只是想知道为什么我的代码无效。我这样做完全错了吗?

window.onload = function random() {
    var links = document.getElementsByTagName('a');
    var colours = new Array("green","red","blue");
    var randomColour = colours[Math.floor(colours.length * Math.random())];
    for (a = 0; a < links.length; a++) {
        links[a].style.color = 'randomColour';
    }
}

1 个答案:

答案 0 :(得分:1)

'randomColor' - &gt; randomColor
使用变量而不是带引号的字符串。此外,为确保每个链接都获得随机颜色,请在循环中生成颜色:

for (var a = 0; a < links.length; a++) {
    var randomColour = colours[Math.floor(colours.length * Math.random())];
    links[a].style.color = randomColour;
}

要最小化设置颜色和解析链接之间的延迟,请绑定DOMContentLoaded事件,或者只是将代码粘贴到<body>的末尾:

http://jsfiddle.net/V6Chb/1/

<a>Test</a>
  ... 
<a>Test</a>
<script>
(function() { // <-- Anonymous function to not leak variables to the global scope
    var links = document.getElementsByTagName('a');
    var colours = ["green", "red", "blue"];
    for (var a = 0; a < links.length; a++) {
        var randomColour = colours[Math.floor(colours.length * Math.random())];
        links[a].style.color = randomColour;
    }
})();