我找到了一些我想使用的代码on fiddle
var tags = [].slice.call(document.querySelector('.tagcloud')
.getElementsByTagName('a'));
tags.forEach(function(el) {
el.style.backgroundColor = randomColor();
});
function randomColor() {
return '#' + (0x1000000 + (Math.random()) * 0xffffff).toString(16).substr(1, 6);
});
但是我将它插入购物车的平台(在他们给我的区域中的JS)并且我收到错误:
Uncaught TypeError: Cannot read property 'getElementsByTagName' of null
代码相当直接,显然适用于小提琴,所以我怀疑也许是因为相关的html还没有生成呢?我认为这与“委托”有关,但我不清楚如何实施。
这是生成的HTML:
<div class="footer_block_content tagcloud">
<a class="tag_level2 first_item"> asd </a>
<a class="tag_level1 item"> rfds </a>
<a class="tag_level1 item"> ewsf </a>
<a class="tag_level3 item"> sdfa</a>
<a class="tag_level1 item"> earf </a>
<a class="tag_level1 item"> sdfae </a>
<a class="tag_level1 last_item"> adfa </a>
</div>
答案 0 :(得分:0)
您好,请检查这是否是您要执行的操作:
<div class="tagcloud">
<a href="#" class="tag-link-79">tag1</a>
<a href="#" class="tag-link-78">tag2</a>
<a href="#" class="tag-link-35">tag3</a>
<a href="#" class="tag-link-32">tag4</a>
<a href="#" class="tag-link-29">tag5</a>
<a href="#" class="tag-link-30">tag6</a>
<a href="#" class="tag-link-34">tag7</a>
<a href="#" class="tag-link-31">tag8</a>
<a href="#" class="tag-link-33">tag9</a>
</div>
<script>
function addColors(){
var tags = document.getElementsByTagName("a");
for(var i=0;i<tags.length;i++){
tags[i].style.backgroundColor = randomColor();
}
}
function randomColor() {
return '#' + (0x1000000 + (Math.random()) * 0xffffff).toString(16).substr(1, 6);
}
document.load = addColors();
</script>