자바스크립트 개발 환경은 Microsoft Visual Studio 2015 버전 HTML 기능 및 Chrome을 이용하고 있습니다.
HTML에서 JavaScript Code를 넣으려면 반드시 <script> 와 </script> 태그 사이에 넣어야한다.
Old JavaScript examples may use a type attribute: <script type="text/javascript">.
The type attribute is not required. JavaScript is the default scripting language in HTML.
예전에는 <script type="~">를 해야했지만 이제는 반드시 하지 않아도 된다.
자바스크립트 코드는 항상 body문 아니면 head문에 존재해야한다.(양쪽에 모두 존재하거나 둘중 하나이거나)
Head에 스크립트가 있는 경우
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <!DOCTYPE html> <html> <head> <title>test title</title> <script> function myFunc() { document.getElementById("test").innerHTML = "Use myFunc() -> Called"; } </script> </head> <body> <h2> JavaScript in Head </h2> <p id = "test">Hello World</p> <button type="button" onclick="myFunc()">클릭!!</button> </body> </html> // This source code Copyright belongs to Crocus // If you want to see more? click here >> | Crocus |
이전에는 아래와 같이 이용했지만, 스크립트를 이용하면 위와 같이 사용이 가능하다.
<button type="button" onclick='document.getElementById("demo").innerHTML = "이렇게!"'>Click</button>
Body에 스크립트가 있는 경우
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <!DOCTYPE html> <html> <head> <title>test title</title> </head> <body> <h2> JavaScript in Body </h2> <p id = "test">Hello World</p> <button type="button" onclick="myFunc()">클릭!!</button> <script> function myFunc() { document.getElementById("test").innerHTML = "Use myFunc() -> Called"; } </script> </body> </html> // This source code Copyright belongs to Crocus // If you want to see more? click here >> | Crocus |
이번에는 .js 자바스크립트 파일을 만들어서 호출하는 방식을 이용해보려 한다.
마치 C에서 include, Java에서 import와 비슷하다.
.js 파일을 호출하는 명령어는 <script src="주소"></script>이다.
외부에 스크립트 파일을 놓아두면 몇가지 장점이 있는데 아래와 같다.
1. HTML 그리고 코드를 분리 시켜둘 수 있다.
2. HTML과 자바스크립트의 가독성을 더 높여준다.
3. 캐시된 자바스크립트 파일이 페이지 로딩 속도를 높여준다.
참고로 script src에서 주소는 상대주소로도 이용이 가능하니 기억해두자.
(이 부분은 검색해보길 바란다.)
.js에 스크립트가 있는 경우
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <!DOCTYPE html> <html> <head> <title>test title</title> <script src="https://tistory4.daumcdn.net/tistory/1636110/skin/images/myFunc2.js"></script> </head> <body> <h2> JavaScript in .js </h2> <p id = "test">Hello World</p> <button type="button" onclick="myFunc()">클릭!!</button> </body> </html> // This source code Copyright belongs to Crocus // If you want to see more? click here >> | Crocus |
'Basic > JavaScript' 카테고리의 다른 글
자바스크립트 연산자 우선순위 (0) | 2017.09.19 |
---|---|
자바스크립트 출력 메소드 사용 방법 (0) | 2017.09.19 |
getElementById() 메소드 이용 방법 (0) | 2017.09.18 |
자바스크립트 옵션 객체 초기화 방법 (0) | 2017.08.31 |
자바스크립트 함수를 이용한 객체 생성 (0) | 2017.08.28 |