'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;
}
})();