jQuery
기존에 복잡했던 클라이언트 측 HTML 스크립팅을 간소화 하기 위해 고안된 JavaScript 라이브러리
적은 양의 코드로 빠르고 풍부한 기능 제공
* 라이브러리: 프로그램, 프로그래밍 언어에 없는 추가적 기능
<연결 방법>
1. jQuery 라이브러리 다운로드하여 external 방식으로 연결
2. CDN(Content Delivery Network) 이용하여 온라인 환경에서 페이지 로딩 시 다운로드 하여 연결(<head> 태그 안에 넣어 사용)
<head>
<!-- 다운 받은 jQuery 라이브러리 추가 -->
<!-- <script src="/jQuery 다운받은 파일 경로"></script> -->
<!-- CDN 방식으로 jQuery 라이브러리 추가 -->
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<!-- 한 가지 방법을 택해 사용하여야 한다. -->
</head>
<body>
<button type="button" id="btn1">자바스크립트 버튼</button>
<button type="button" id="btn2">제이쿼리 버튼</button>
<script>
document.getElementById("btn1").addEventListener("click", function(){
alert("자바스크립트 버튼이 클릭되었습니다.")
})
$("#btn2").on("click", function(){
alert("제이쿼리 버튼이 클릭되었습니다.")
})
</script>
</body>
HTML 해석 순서와 window.onload, jQuery ready()함수
HTML 문서는 위에서 아래로 항상 순서대로 해석된다. 즉, 아래쪽에서 작성되어 아직 해석이 안 된 코드는 사용할 수 없다.
window.onload
- HTML(현재창)이 모두 로딩이 되었을 때 라는 이벤트리스너로, 문서 내용을 모두 해석한 후 마지막에 함수 실행
- 단점: 한 페이지 내에서 한 번만 작성할 수 있음(여러번 작성 시 마지막 내용만 수행)
jQuery ready()함수
- HTML 문서 로딩이 완료된 후 수행할 기능을 작성하는 함수
- window,onload의 단점인 한 번만 작성 가능한 문제점 보완 = 여러번 작성 가능
* 작성방법
1) jQuery(document).ready(function(){ 코드 })
2) $(document).ready(function(){ 코드 })
3) $(function(){ 코드 })
window.ready() 함수 확인하기
<script>
// document.getElementById("test").innerText = "HTML 해석 순서 테스트"
// * Uncaught TypeError: Cannot set properties of null (setting 'innerText')
// #test 아이디를 가지는 요소가 해석되기 전에 작성 된 코드는 정상적으로 수행되지 못한다.
window.onload = function(){
document.getElementById("test1").innerText = "HTML 해석순서 테스트 "
} // 화면에 해당 문구 출력
window.onload = function(){
console.log("마지막으로 작성된 onload")
} // 마지막으로 작성된 함수만 실행되므로, 위에서 실행되었던 innerText는 사라진다.
</script>
<p id="test">
ready() 함수 확인하기
<script>
jQuery(document).ready(function(){
$("#test").text("ready()함수 테스트")
})
jQurey(document).ready(function(){
$("#test").css("backgroundColor", "pink")
})
jQurey(document).ready(function(){
$("#test").css("fontSize", "30px")
document.getElementById("test").style.fontWeight = "bold"
document.getElementById("test").innerText ++ "...새로운 내용 추가!"
})
</script>
<p id="test"></p>
'JS > jQurey' 카테고리의 다른 글
2. jQuery 선택자 (0) | 2023.03.06 |
---|