Javascript/기초공부
[Javascript: 모듈(Module)] 모듈화 / 라이브러리
jisun_rea
2020. 3. 11. 15:18
모듈화 예제: greeting.js, main.html
// greeting.js
function welcome() {
return 'hello world';
}
// main.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="greeting.js"></script> // 파일 불러오기
</head>
<body>
<script>
alert(welcome()); // 함수 호출
</script>
</body>
</html>
* script 태그에 src라는 속성을 확인하여 그 속성값에 해당하는 파일을 읽어와서 script 태그 안에 넣는 것과 같은 효과를 낸다.
라이브러리: jQuery 예제
jQuery
What is jQuery? jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
jquery.com
Download jQuery -> Download the uncompressed, development jQuery 3.4.1 -> copy해서 -> jquery.js 파일을 만들고 paste
execute 버튼을 누르면 empty 리스트가 coding everybody로 바뀌게 해보자.
// jQuery.demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="jquery.js"></script>
</head>
<body>
<ul id="list">
<li>empty</li>
<li>empty</li>
<li>empty</li>
<li>empty</li>
</ul>
<input type="button" value="execute" id="execute_btn" />
<script>
$('#execute_btn').click(function(){
// id값이 list인 태그의 하위의 li태그
$('#list li').text('coding everybody');
});
</script>
</body>
</html>