귀농 전까지 쓰는 개발 일지

[JavaScript] 개요_출력 본문

공부/JavaScript

[JavaScript] 개요_출력

한호잉 2022. 1. 17. 14:02

(1) JavaScript 적용 방법

- HTML 문서 내 <script>

<!DOCTYPE html>
<html>
<head></head>
<body>
   <p id="demo">text</p>
   <button type="button" onClick="change()">change</button>

   <script>
   function change(){
      document.getElementById("demo").innerHTML = "change";
   }
   </script>
</body>
</html>
 

- 외부 파일

<!DOCTYPE html>
<html>
<head></head>
<body>
   <p id="demo">text</p>
   <button type="button" onclick="change()">change</button>
   <script src="script.js"></script>
</body>
</html>

function change() {
   document.getElementById("demo").innerHTML = "change";
}
 

 

(2) 출력

- innerHTML : html 요소에 출력

<p id="demo"></p>
<script>
   document.getElementById("demo").innerHTML = 5 + 6;
</script>
 
innerHTML출력

 

 

 
 - document.write() : body에 출력 / Popup 창에 동적으로 내용 보여주기 위해 사용 / 기존 내용 모두 삭제됨
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<button type="button" onclick="document.write(5 + 6)">
   Try it
</button>
 
document.write()

 

- window.alert() : 경고창에 출력 (window 생략 가능) / 알림메시지 출력 위해 경고 상자 이용

<script>
   alert(5 + 6);
</script>
window.alert()

 

- console.log() : 브라우저 콘솔(개발자 도구)에 쓰기 / 디버깅 위해 사용

<script>
   a = 5;
   b = 6;
   c = a + b;
   console.log(c);
</script>
 
console.log()

 

- window.print(): 현재 창 내용 프린터 통해 출력

<button onclick="window.print()">Print this page</button>