웹 프로그래밍 기초/자바스크립트 맛보기

HTML과 자바스크립트 연결 2

별초롱언니 2025. 4. 1. 14:05

외부 자바스크립트 불러오기

<head>나 <body>섹션의 <script> 태그에 있는 src속성 값으로 자바스크립트 파일을 지정하여 불러온다.

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>HTML 외부 연결</title>
</head>
<body>
  <script src="now.js">
  </script>
</body>
</html>

html파일

var now = new Date();
document.write("<h1>" + now + "<h1>");

js파일

 

 

인라인 자바스크립트

자바스크립트가 HTML 태그 내에 존재하는 다른 태그의 이벤트 속성으로 삽입될 수 있다. 즉, 요구되는 이벤트가 발생하였을 때 실행되는 자바스크립트를 삽입하는 경우이다. 이 경우는 <script> 태그를 사용하지 않는다. 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <input type="button" onclick="document.write('Hello JavaScript')" value="Click Me!">
</body>
</html>

 

See the Pen Untitled by byeolchorong (@byeolchorong) on CodePen.