바이올린 에서 사용하고 싶은 코드를 찾았습니다.
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>
브라우저가 순서대로 렌더링하고 즉시 표시되는 코드를 실행함에 따라 이러한 코드를에 넣는 것 같습니다 <a>
. 스크립트를 함수로 래핑하고 jsfiddle처럼 해당 함수를 window.onload에 할당 할 수 있습니다.
window.onload = function() {
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);
};
};
추가 참고 사항, ')'
끝에 를 넣으면 randomColor
오타가 아닌 경우 구문 오류가 발생합니다.
a {
display: inline-block;
color: #fff;
padding: 5px 10px;
}
<script>
window.onload = function() {
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);
};
}
</script>
<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>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다