Javascript에서 document.body가 null 인 이유는 무엇입니까?
다음은 간단한 HTML 문서입니다.Chrome 콘솔에서이 오류를 알리는 이유 :
"Catch되지 않은 TypeError :"의 'appendChild'메소드를 호출 할 수 없습니까?
null
<html>
<head>
<title>Javascript Tests</title>
<script type="text/javascript">
var mySpan = document.createElement("span");
mySpan.innerHTML = "This is my span!";
mySpan.style.color = "red";
document.body.appendChild(mySpan);
alert("Why does the span change after this alert? Not before?");
</script>
</head>
<body>
</body>
</html>
본문은 아직 정의되지 않았습니다. 일반적으로 이러한 요소를 사용하는 자바 스크립트를 실행하기 전에 모든 요소를 작성하려고합니다. 이 경우
head
섹션을 사용 하는 자바 스크립트 가
body
있습니다. 쿨하지 않아.이 코드를
window.onload
핸들러 에 랩 하거나 태그
뒤에
배치하려고 합니다
<body>
(
언급 한대로 ).
<head>
<title>Javascript Tests</title>
<script type="text/javascript">
window.onload = function() {
var mySpan = document.createElement("span");
mySpan.innerHTML = "This is my span!";
mySpan.style.color = "red";
document.body.appendChild(mySpan);
alert("Why does the span change after this alert? Not before?");
}
</script>
</head>
.
body
요소가로드 되기 전에 스크립트가 실행되고 있습니다.이 문제를 해결하는 몇 가지 방법이 있습니다.
- DOM로드 콜백으로 코드를 래핑하십시오.그렇게하면
요소가로드 될 때 콜백이 실행됩니다 .body
필요에 따라document.addEventListener('DOMContentLoaded', function () { // ... // Place code here. // ... });
이벤트 리스너를load
객체에 연결할 수도 있습니다 .window
window.addEventListener('load', function () { // ... // Place code here. // ... });
와DOMContentLoaded
이벤트 의 차이점 에 .load
-
의 이벤트 리스너에 로직을 래핑하십시오
DOMContentLoaded
. <script>
요소 의 위치를 이동하고 마지막으로 JavaScript를로드 하십시오 .<!DOCTYPE html> <html> <head></head> <body> <p>Some paragraph</p> <!-- End of HTML content in the body tag --> <script> <!-- Place your script tags here. --> </script> </body> </html>
-
현재
<script>
요소가<head>
문서 요소에 로드되고 있습니다. 이는body
로드 되기 전에 실행됨을 의미합니다 .Google 개발자<script>
는 자바 스크립트가 처리되기 전에 모든 HTML 콘텐츠가 렌더링되도록 태그를 페이지 끝으로 이동하는 것이 좋습니다 .
Add your code to the onload event. The accepted answer shows this correctly, however that answer as well as all the others at the time of writing also suggest putting the script tag after the closing body tag, .
This is not valid html. However it will cause your code to work, because browsers are too kind ;)
See this answer for more info Is it wrong to place the <script> tag after the </body> tag?
Downvoted other answers for this reason.
Or add this part
<script type="text/javascript">
var mySpan = document.createElement("span");
mySpan.innerHTML = "This is my span!";
mySpan.style.color = "red";
document.body.appendChild(mySpan);
alert("Why does the span change after this alert? Not before?");
</script>
after the HTML, like:
<html>
<head>...</head>
<body>...</body>
<script type="text/javascript">
var mySpan = document.createElement("span");
mySpan.innerHTML = "This is my span!";
mySpan.style.color = "red";
document.body.appendChild(mySpan);
alert("Why does the span change after this alert? Not before?");
</script>
</html>
Browser parses your html from top down, your script runs before body is loaded. To fix put script after body.
<html>
<head>
<title> Javascript Tests </title>
</head>
<body>
</body>
<script type="text/javascript">
var mySpan = document.createElement("span");
mySpan.innerHTML = "This is my span!";
mySpan.style.color = "red";
document.body.appendChild(mySpan);
alert("Why does the span change after this alert? Not before?");
</script>
</html>
document.body
is not yet available when your code runs.
What you can do instead:
var docBody=document.getElementsByTagName("body")[0];
docBody.appendChild(mySpan);
참고URL : https://stackoverflow.com/questions/9916747/why-is-document-body-null-in-my-javascript
'programing' 카테고리의 다른 글
파일에서 행의 마지막 열 인쇄 (0) | 2020.08.11 |
---|---|
자바 스크립트 for 루프 내부의 비동기 프로세스 (0) | 2020.08.11 |
Internet Explorer에서 콘솔 로깅을 사용하려면 어떻게해야합니까? (0) | 2020.07.18 |
파이썬에서 EAFP 원칙은 무엇입니까? (0) | 2020.07.18 |
호스트의 도커 장착 볼륨 (0) | 2020.07.18 |