티스토리 뷰
깃허브 JQUERY 프로젝트 확인:
https://github.com/BigJadeStone/JQUERY
GitHub - BigJadeStone/JQUERY
Contribute to BigJadeStone/JQUERY development by creating an account on GitHub.
github.com
-자바스크립트
1. javaScript vs Jquery
2. Jquery사용법
* JQuery 는
자바스크립트르 ㄹ더 간편하게 사용하게 해주는 자바스크립트 라이브러리이다.
*Jquery 다운받기
- 제이쿼리 홈페이지 가서 다운로드.
다운로드 누르고 나오는 창에서
마우스 오른쪽 누르고 다른 이름으로 파일 저장 후
아래와 같이 파일을 프로젝트에 갖다 놓은 후 .
페이지에서 스크립트를 걸어준다 ( src 에는 제이쿼리 파일의 경로를 적어주면 됨)
------------------------------------------------------------------------------------------------------------
★ ${"선택자"}.제이쿼리함수()를 이용해서 태그를 제어합니다. ★
* 제이쿼리 시작객체 내부를 들여다보면 사용할 수 있는 제이쿼리 함수들을 살펴볼 수 있다.
// ${"선택자로"} 요소를 얻으면, 제이쿼리 시작객체를 반환해줍니다.
console.log($("#melon"));
* 태그에 [0] 을 붙여주면 순수한 엘리먼트를 가져와줌.
console.log($("#melon")[0]); //순수한 엘리먼트
jquery01.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- jquery -->
<script src="js/jquery-3.6.3.min.js"></script>
</head>
<body>
<input type="text" id="melon" value="홍길동">
<input type="text" class="apple" value="apple">
<script>
// ${"선택자로"} 요소를 얻으면, 제이쿼리 시작객체를 반환해줍니다.
console.log($("#melon"));
//${"선택자"}.제이쿼리함수()를 이용해서 태그를 제어합니다.
console.log($("#melon")[0]); //순수한 엘리먼트
//값을 얻음
var result = $("#melon").val();
console.log(result)
//값을 변경
$("#melon").val("변경할값");
//값을 변경
$(".apple").val("변경할값");
</script>
</body>
</html>
<body>
<input type="text" class="test1" id="xx">
<img src="#" class="test2">
<img src="#" class="test3" width="" height="">
<script>
// var x = document.querySelector(".tset1").id;
var x = $(".test1").attr("id"); //id 속성을 얻음
console.log(x);
//src 값을 변경
$(".test2").attr("src", "값을변경");
//여러속성을 한번에 변경
$(".test3").attr({
src: "값을변경",
width: "200",
height: "200"
})
</script>
</body>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- jquery -->
<script src="js/jquery-3.6.3.min.js"></script>
</head>
<body>
<h3>스타일제어</h3>
<ul class="test1">
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
<div class="box">box</div>
<div class="box">box</div>
<div class="box">box</div>
<div class="box">box</div>
<script>
//
// var li = document.querySelectorAll(".test1 > li");
// for(var i = 0; i<li.length; i++){
// li[i].style.backgroundColor = "red";
// }
$(".test1 > li").css("backgroundColor", "red");
//css속성 확인
var color = $(".test1 > li").css("backgroundColor");
console.log(color);
//css속성을 한번에 변경
$(".box").css({
backgroundColor : "red",
width: "200px",
height: "200px",
display: "inline-block"
})
</script>
</body>
</html>
* html() 함수 -> 많이 쓰이니 잘 알아두기 ★
- 자바스크립트의 innerHTML 과 같은 기능.
* text() 함수는 잘 사용 안함.
- 매개변수에 넣어준 값을 innerHTML 자리에
순수한 텍스트로 넣어줌.
<body>
<div class="test1"></div>
<div class="test2"></div>
<script>
//js
// document.querySelector(".test1").innerHTML = "<a href='#'>kkk</a>";
//값을 변경
$(".test1").html("<a href='#'>kkk</a>");
$(".test1").html(""); //공백으로
$(".test1").html("홍길동");
//값을 얻음
var result = $(".test1").html();
console.log(result);
//text() - 순수한 텍스트로 인식
$(".test2").text("<a href='#'>kkk</a>"); //텍스트로
</script>
</body>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- jquery -->
<script src="js/jquery-3.6.3.min.js"></script>
</head>
<body>
<button id="btn" class="btn btn-default">클래스 조작</button>
<script>
//js
// document.getElementById("btn").classList.add("myBtn"); //클래스추가
// document.getElementById("btn").classList.remove("myBtn"); //클래스삭제
$("#btn").addClass("myBtn"); //클래스 추가
$("#btn").removeClass("myBtn"); //클래스 삭제
</script>
<button id="tog" class="dark">토글형식</button>
<script>
$("#tog").click(function(){
console.log(this);
// this.classList.toggle("dark");
$(this).toggleClass("dark");
})
</script>
</body>
</html>
* 위에 있는 함수들은 웬만하면 잘 기억해두기.
정말 많이 쓰임.
*closest("선택자") 함수 ★★★★★
매개변수에 넣어준 선택자에 해당하는 것중에 가장 가까운 부모요소를 찾아줌.
*find("td") 함수 ★★★★★
자식요소 td들을 다 찾아줌
*children() 함수
- 모든 자식들 ( 직계 자식) 찾아줌.
*last() 함수
자식 요소 중 마지막 자식요소 찾아줌.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- jquery -->
<script src="js/jquery-3.6.3.min.js"></script>
</head>
<body>
<table>
<tr>
<th>번호</th>
<th>이름</th>
<th>버튼</th>
<th>테스트</th>
</tr>
<tr>
<td>1</td>
<td>홍길동</td>
<td>
<button type="button" class="btn">버튼</button>
</td>
<td>
<span><i class="test">테스트1</i></span>
<span >테스트2</span>
</td>
</tr>
<tr>
<td>2</td>
<td>이순신</td>
<td>
<button type="button" class="btn">버튼</button>
</td>
<td>
<span><i class="test">테스트1</i></span>
<span >테스트2</span>
</td>
</tr>
</table>
<script>
/*
1. closest("선택자") - 최근접 단일 부모선택
2. prev() - 이전형제
3. next() - 다음형제
4. siblings() - 모든형제
5. first() - 첫번째 자식
6. last() - 마지막 자식
7. children() - 모든 자식들
8. finde("선택자") - 특정 자식
*/
$(".btn").click(function(e){
//this or e.target
// console.log(this);
// console.log(e.target);
// console.log($(this).closest("td"));
// console.log($(this).closest("tr")); //최근접 tr 태그
// console.log($(this).closest(".xxx")); //최근접 xxx 클래스
// console.log($(this).closest("td").prev()); //이전형제
// console.log($(this).closest("td").next()); //다음형제
// console.log($(this).closest("td").siblings()); //모든형제
// console.log($(this).closest("tr").children()); //모든 자식들
// console.log($(this).closest("tr").children().first()); //첫째
// console.log($(this).closest("tr").children().last()); //막내
console.log($(this).closest("tr").find("span")); // span 태그 자식
})
</script>
</body>
</html>
* $().ready()
- window.onload 와 비슷함 ( window.onload는 페이지를 다 로드(읽는것)하고나서 마지막에 작업이 수행됨, 한 페이지에 단 한번만 사용가능).
반면에
().ready() 는 페이지 로드가 다 끝나고 나서 수행되는건 마찬가진데 window.onload 와 다른점은
여러 번 사용 가능하다는 점 (window.onload의 상위 호환이라고 보면 됨. )
위 사진을 보면 스크립트가 참조하는 태그보다 위에 있기 때문에
스크립트에서 태그를 참조할 때 태그는 아직 존재하지 않는 것이기 때문에
참조가 안됨. 따라서 이럴 때 위에있는
js의 window.onload 나
제이쿼리의 $(document).ready() 가 쓰이는 것 ( 페이지를 다 읽고나서 script 가 실행됨)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- jquery -->
<script src="js/jquery-3.6.3.min.js"></script>
</head>
<body>
<script>
//js - 페이지 로드 이후 실행하는 이벤트 - 페이지별로 1개만 사용가능
// window.onload = function(){
// console.log($("#btn"))
// }
//jquery - 페이지 로드 이후 실행하는 함수 - 여러개 사용가능
$(document).ready(function(){
console.log($("#btn"))
})
$(document).ready(function(){
console.log(2);
})
</script>
<button id="btn">도큐먼트레디</button>
</body>
</html>
* 일반적으로 이벤트 걸기
* 이벤트 위임방식
이벤트를 위임하는 경우는 언제인가 ?
- 위에 a태그는 아직 생성되지 않은 태그
하지만 이벤트를 달아주고 싶으면
부모 태그인 id가 replyList 인 div 태그에다가 이벤트를 위임하도록 해준다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- jquery -->
<script src="js/jquery-3.6.3.min.js"></script>
</head>
<body>
<button id = "btn">이벤트등록</button>
<input type="text" id="tag">
<select id="sel">
<option>1</option>
<option>2</option>
</select>
<div style="background-color: red;" id="mos">마우스이벤트</div>
<script>
//클릭
$("#btn").click(function(){
console.log("click");
})
//키관련이벤트
$("#tag").keyup(function(){
console.log("key~");
})
//체인지
$("#sel").change(function(){
console.log("chan");
})
//마우스관련 이벤트
$("#mos").mouseenter(function(){
console.log("mouse enter");
})
$("#mos").mouseleave(function(){
console.log("mouse leave");
})
</script>
<hr/>
<h3>이벤트 위임방식 on()</h3>
<div id="box">
</div>
<script>
setTimeout(function(){
var str = "";
str += "<a href= '#'>태그1</a>";
str += "<a href= '#'>태그2</a>";
str += "<a href= '#'>태그3</a>";
$("#box").html(str);
},2000); //2초 뒤에 태그생성
//어림도없지
// $("a[href='#']").click(function(){
// console.log("a링크 실행");
// })
//(이벤트종류, 위임시킬선택자, 핸들러)
$("#box").on("click","a",function(){
event.preventDefault(); //고유이벤트 중지
console.log("a링크 실행");
})
</script>
</body>
</html>
* 주요속성
- contentType (위에 사진에 누락되어 있음) : 내가 던지는 데이터 타입.
contentType를 반드시 적어야 하는 경우는
post 방식으로 데이터를 숨겨서 전달하는 경우에
이 타입이 어떤 타입인지 알려주기 위해서 적어주는 것.
- dataType: 내가 받을 데이터에대한 타입.
ajax 함수 참고 링크 :
http://www.tcpschool.com/ajax/ajax_jquery_ajax
* 서버에 보내는 요청
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- jquery -->
<script src="js/jquery-3.6.3.min.js"></script>
</head>
<body>
<button id="btn">에이젝트</button>
<script>
$("#btn").click(function(){
//ajax
$.ajax({
url:"http://localhost:8383/getAjax", //요청주소
type : "post", //요청타입
data : JSON.stringify({id: "aaa123", name: "홍길동"}), //보낼데이터
contentType : "application/json", //보내는 데이터에대한 타입(필수) -> 안적으면 기본 form 방식
dataType: "json", //json, xml, text, html, ...등등 (받는데이터에 대한 타입)(옵션) -> 안적으면 기본 제이슨
success: function(result){ //성공시 콜백
console.log(result);
},
error : function(err){ //실패시 콜백
console.log(err);
}
})
})
</script>
<hr/>
<input type="text" name="topic" class="data">
<button class="button">get방식</button>
<script>
//버튼을 클릭하면 get방식으로 ajax처리를 합니다.
//getAjax2/토픽값 요청처리합니다.
//응답데이터는 "success"
// console.log($(".button")[0]);
$(".button").click(function(){
// console.log( $(".data").val());
var data = $("input[name='topic']").val();
$.ajax({
url:"http://localhost:8383/getAjax2/" + data,
type: "GET", //요청타입
success: function(result){ //성공시 콜백
console.log(result);
},
error : function(err){ //실패시 콜백
console.log(err);
}
})
})
</script>
</body>
</html>
* 서버측 컨트롤러 (스프링 부트)
//jquery - ajax예시
@CrossOrigin({"http://127.0.0.1:5501",
"http://localhost:5501"})
@PostMapping("/getAjax")
public Map<String, Object> getAjax(SimpleVO2 simpleVo2){
//받은 데이터
System.out.println(simpleVo2.toString());
//보내는 데이터
Map<String, Object> map = new HashMap<>();
SimpleVO2 vo = new SimpleVO2("aaa123", "홍길동", "1");
map.put("total", 100);
map.put("data", vo);
return map;
}
@CrossOrigin("*") //전부허용
@GetMapping("/getAjax2/{topic}")
public String getAjax2(@PathVariable("topic") String topic){
System.out.println(topic);
return "success";
}
'Spring 부트' 카테고리의 다른 글
23-02-22) 스프링 부트 11강 1편 - 로그인기능 <세션 , redirect(redirectAttributes) > (0) | 2023.02.22 |
---|---|
23-02-21) 스프링부트 10강 - 파일 업로드 (0) | 2023.02.22 |
23-02-16) 스프링부트 7강 - REST API (0) | 2023.02.16 |
23-02-15) 스프링부트 6강 - 판매자매니저 ( 등록, 조회, 페이지네이션, amount 조절, 검색 기능) (0) | 2023.02.15 |
23-02-14) 스프링부트 6강 - 판매자매니저 (페이지 나누기 - 템플릿형식으로) (0) | 2023.02.14 |
- Total
- Today
- Yesterday
- 자바
- JS ES6 문법
- 오코노라멘
- 박문석 선생님
- api 활용
- 중앙정보처리학원
- output 스트림
- 다중 반복문
- 조건문
- 배열의 정렬
- 국비학원
- 내포 클래스
- 데이터베이스 수업
- 국비지원 학원 수업 내용
- 박인욱 강사님
- 가비지 콜렉팅
- 알람 시계 문제
- 자바스크립트 ES6 문법
- 자바수업
- 배열 삭제
- 자바#자바수강기록
- 강남역 12번 춣구
- FOR문
- 자바 api
- input 스트림
- nasted class
- interface #자바
- 국비학원 수업
- 배열과 탐색
- 강남 중앙정보처리학원
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 26 | 27 | 28 | 29 | 30 | 31 |