2017-12-29 33 views
0

누구나 을 표시 할 수 있습니까? document.getElementById("ibody").innerHTML=...을 표시하는 코드가 작동하지 않는 이유는 무엇입니까?이 코드가 getElementById와 제대로 작동하지 않는 이유는 무엇입니까?

<script type="text/javascript"> 
    var v=new Date(); 
    document.write("Avec document.write() = "+v); 
    window.alert("Avec window.alert() = "+v); 
    alert("Avec alert() = "+v); 
    console.log("Avec console.log = "+v); 
    document.getElementById("ibody").innerHTML= 
     "Avec getElementById() ds DIV = "+v 
</script> 

<body id="ibody"></body> 
+1

이 소스 코드를 편대 decleared 몸에서 자바 스크립트 코드를 유지, 그리고 우리에게 당신의 HTML 소스를 보여 코드. –

+0

(https://stackoverflow.com/questions/1829925/javascript-getelementbyid-not-working) – Phylogenesis

답변

0

코드를 실행하는 시점에서 <body> 요소가 존재하지 않기 때문에.

는 DOM이로드가 완료되면 실행되는 이벤트 처리기에서 코드 블록 포장보십시오 :

<script type="text/javascript"> 
    document.addEventListener(
     'DOMContentLoaded', 
     function() { 
      var v=new Date(); 
      document.write("Avec document.write() = "+v); 
      window.alert("Avec window.alert() = "+v); 
      alert("Avec alert() = "+v); 
      console.log("Avec console.log = "+v); 
      document.getElementById("ibody").innerHTML= 
       "Avec getElementById() ds DIV = "+v 
     } 
    ); 
</script> 
0

+0

을 페이지 하단에도 유지할 수 있습니다. 페이지 하단에 js 코드를 유지하는 것이 가장 좋은 방법이며