0

只是想知道为什么我的代码不起作用。我这样做完全错了吗?

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';
    }
}
4

1 回答 1

1

'randomColor'-> 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;
    }
})();  
于 2012-04-15T16:22:33.773 回答