<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
</body>
</html>
HTML에서 JS Code는 script Tag사이에 들어간다.
scripts는 HTML의 <head> or <body> Tag섹션 사이에 위치한다.
JS 함수는 HTML의 <head> Tag섹션 사이에 위치한다.
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h2>Demo JavaScript in Head</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
RUN 결과.
버튼 클릭 시 결과.
<head> Tag에 JS를 삽입, .innerHTML을 사용하여 'demo'의 파라미터를 변경.
<!DOCTYPE html>
<html>
<body>
<h2>Demo JavaScript in Body</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
결과는 ③과 같음
<body> Tag에 JS를 삽입, .innerHTML을 사용하여 'demo'의 파라미터를 변경.
<!DOCTYPE html>
<html>
<body>
<h2>Demo External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>This example links to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>
<script src="myScript.js"></script>
</body>
</html>
결과는 ③과 같음, 참고 하자 :
<p>This example links to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>
Script는 외부 파일로도 존재&참조 가능. 형식 : .js
외부 script를 사용하기 위해, <script> Tag 속성중 하나인 src에 파일명을 입력해야 한다.
<script src="myScript.js"></script>
외부 script 역시 <head> or <body> tag 사이에 삽입할 수 있다.
외부 script는 3가지 다른 방법으로 참조 가능하다.
<!DOCTYPE html>
<html>
<body>
<h2>External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Click Me</button>
<p>This example uses a full web URL to link to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>
<script src="https://www.w3schools.com/js/myScript.js"></script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>This example uses a file path to link to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>
<script src="/js/myScript.js"></script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Demo External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>This example links to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>
<script src="myScript.js"></script>
</body>
</html>
HTML File Paths. 파일 경로에 대한 더 많은 자료는 아래 링크 참조
(참조 : https://www.w3schools.com/html/html_filepaths.asp)