티스토리 뷰

41기 개발자과정

20211112 제이쿼리 02

segment 2021. 11. 12. 10:08

제이쿼리 배열  관련 메서드 실습

 

1. 실습. 아래의 버튼을 클릭시

ul 하위 요소의 li텍스트 요소가 'Y' 일 경우 'N' 으로 , 'N' 일 경우 'Y' 로 변경되는 코드를 작성하고 실행하여라.

<button type="button" id="textChange">반전</button>
	<ul id="ulText">
		<li>Y</li>
		<li>Y</li>
		<li>N</li>
		<li>Y</li>
		<li>N</li>
	</ul>
<script type="text/javascript">
	var liObj =  $('#ulText li');
		$(function(){
			$('#textChange').click(function(){
				liObj.each(function(i){
					if($(this).text()=='Y'){
						$(this).text('N');
					}else{
						$(this).text('Y');
					}
				});
			});
		});
	
	</script>

속성 상태에 따른 탐색 선택자, 속성 상태변화 및 확인 메서드

1. 속성 상태에 따른 탐색 선택자

- 각 태그의 속성으로 상태를 변화시키는 속성 (checked, selected)
- $(':상태속성명'),  $('선택자:상태속성명')

 

<input type="checkbox" checked>
	<select>
		<option selected></option>
	</select>
<script type="text/javascript">
		console.log($('input:checked'), 'checked')
		console.log($('select option:selected'), 'selected')
	
	</script>

 

 

1-1. 1개 이상 체크 확인하기

<label>
	<input type="checkbox" class="addr" name="addr" value="전주"> 전주
</label>
	
<label>
	<input type="checkbox" class="addr" name="addr" value="군산"> 군산
</label>
	
<label>
	<input type="checkbox" class="addr" name="addr" value="익산"> 익산
</label>
<button type="button" id="checkBtn">확인</button>

 

 

 

 

$(function(){
		$('#checkBtn').click(function(){
		var addr = $('.addr:checked'); //체크될 때 마다 상태가 바뀌기 때문에 안에 선언해야한다.
			if(addr.length > 0){
				alert('1개 이상 선택이 되었습니다');
			}else{
				alert('최소 1개 선택 하셔야 합니다.');
			}
		});
	});

<- 체크박스 1개 선택시. 배열로 반환이 된다.

배열의 길이가 0 이상이면 체크박스가 선택된 것이다.

 

 

 

2. 속성 상태 변화 및 확인 메서드

- .prop() -> 속성 상태를 확인하거나 변경하는 메서드

<label>
	<input type="checkbox" class="addr2" name="addr2" value="전주"> 전주
</label>
<input type="text" id="myReadonly" readonly>
	
<button type="button" id="propBtn">확인</button>
<button type="button" id="propCheckBtn">변환</button>

 

$(function(){
			var addr2 = $('.addr2');
			var myReadonly = $('#myReadonly');
			$('#propBtn').click(function(){
				/*
					.prop('속성상태명') -> 속성상태를 확인하고 
                    속성 상태가 적용되어있다면 true
					아니라면 false 값이 반환된다.
					.prop('속성상태명', true) -> 강제변환
					.prop('속성상태명', false) -> 강제해제
				*/
				console.log(addr2.prop('checked'));
				console.log(myReadonly.prop('readonly'));
			});
			$('#propCheckBtn').click(function(){
				if(addr2.prop('checked')){
					addr2.prop('checked', false);
				}else{
					addr2.prop('checked', true);
				}
				
				if(myReadonly.prop('readonly')){
					myReadonly.prop('readonly', false);
				}else{
					myReadonly.prop('readonly', true);
				}
			});
		});


.prop('속성상태명') -> 속성상태를 확인하고 속성 상태가 적용되어있다면 true, 아니라면 false 값이 반환된다.
.prop('속성상태명', true) -> 강제변환
.prop('속성상태명', false) -> 강제해제

< - 전주가 선택되어 있을 때

 

 

- console.log(addr2.prop('checked')); ---> 속성상태를 확인하고 속성 상태가 적용되었으므로 true
- console.log(myReadonly.prop('readonly')); ---> true

 


2. 실습. 아래의 버튼에 알맞는 기능을 구현하도록 하여라.
#allCheck 클릭시 체크되어 있다면 아래의 체크박스 '전체 체크',  해제시 '전체 해제' 기능 추가

<button type="button" id="checkDel"> 선택된 행 삭제</button>
	
	<table border="1">
		<thead>
			<tr>
				<th>
					<input type="checkbox" id="allCheck">
				</th>
				<th>제목</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td>
					<input type="checkbox" class="listCheck">
				</td>
				<td>제목입니다.</td>
			</tr>
			<tr>
				<td>
					<input type="checkbox" class="listCheck">
				</td>
				<td>제목입니다.</td>
			</tr>
			<tr>
				<td>
					<input type="checkbox" class="listCheck">
				</td>
				<td>제목입니다.</td>
			</tr>
			<tr>
				<td>
					<input type="checkbox" class="listCheck">
				</td>
				<td>제목입니다.</td>
			</tr>
			<tr>
				<td>
					<input type="checkbox" class="listCheck">
				</td>
				<td>제목입니다.</td>
			</tr>
			<tr>
				<td>
					<input type="checkbox" class="listCheck">
				</td>
				<td>제목입니다.</td>
			</tr>
		</tbody>
	</table>

전체)

$(function(){
		var listCheck = $('.listCheck');
		var allCheck = $('#allCheck');
		var checkDel = $('#checkDel')
		allCheck.click(function(){
			if(allCheck.prop('checked')){
				listCheck.prop('checked', true);
			}else{
				listCheck.prop('checked', false);
			}
		});
		checkDel.click(function(){			
			/* 	listCheck.each(function(){
					if($(this).prop('checked')){
						$(this).parents('tr').remove();
					}
				}); */
				$('.listCheck:checked').each(function(){
					$(this).parents('tr').remove();
				});
			});
		});

 

체크)

allCheck를 클릭 했을 때, 

allCheck가 체크되어 있다면 listCheck 의 checked 상태속성을 true(체크됨) 으로 변경한다.

체크되어있지 않다면 false(체크안됨)으로 변경한다.

allCheck.click(function(){
			if(allCheck.prop('checked')){
				listCheck.prop('checked', true);
			}else{
				listCheck.prop('checked', false);
			}
		});

 

행삭제)

checkDel이 클릭되었을 때,

listCheck 가 체크되어 있는 상태라면 체크된 자신의 부모인 tr을 찾아서 삭제한다.

checkDel.click(function(){			
			/* 	listCheck.each(function(){
					if($(this).prop('checked')){
						$(this).parents('tr').remove();
					}
				}); */
				$('.listCheck:checked').each(function(){
					$(this).parents('tr').remove();
				});
			});

속성 조작 메서드

- .attr() -> 선택된 객체에 속성의 값을 가지고 오거나 속성을 추가 및 속성값을 변경한다.
- .prop() -> 속성상태 값을 추가하거나 변경한다.
- .removeAttr() -> 선택된 객체의 속성을 제거한다.
- .css() -> 선택된 객체의 style 요소를 변경 및 추가한다.

 

<button type="button" id="myAttr1" data-aaa="aaa">속성 확인</button>
<button type="button" id="myAttrDel" >속성 제거</button>
	$(function(){
			$('#myAttr1').click(function(){
				//인수 첫번째 자리는 속성명
				console.log($(this).attr('id'))
				//인수 두번째 자리 - 속성의 값
				$(this).attr('class', 'my-class');
				$(this).attr('readonly', true);
				//없는 속성 생성하기
				$(this).attr('data-myname', '홍길동');
				console.log($(this).attr('data-myname'));
			});
			$('#myAttrDel').click(function(){
				//속성 제거하기
				$('#myAttr1').removeAttr('date-aaa');
			});
		})

 

attr 활용 예시 1.

<form id="myForm"></form>
<button type="button" id="addProcess">저장</button>
<button type="button" id="delProcess">삭제</button>
<script type="text/javascript">
		$(function(){
			var myForm = $('#myForm');
			$('#addProcess').click(function(){
				myForm.attr('action', '/user/addProcess')
				//.submint();
			});
			$('#delProcess').click(function(){
				myForm.attr('action', '/user/delProcess')
				//.submint();
			});
		});
	</script>

 

attr 활용 예시 2.

<input type="radio" name="userName" value="홍길동" data-age ="20" data-addr = "전주">홍길동
<input type="radio" name="userName" value="이순신" data-age ="25" data-addr = "군산">이순신
<script type="text/javascript">
		$(function(){
			$('input[name=userName]').click(function(){
				//var userName = $(this).attr('value');
				var userName = $(this).val();
				var age = $(this).attr('data-age');
				var addr = $(this).attr('data-addr');
				console.log(userName, age,addr);
			});
		});
</script>

css

<div id="textPrint">텍스트 색상 변경하기</div>
	<button type="button" id="colorChange">색상변경</button>
<script type="text/javascript">
	/*
		람다표현식
		function(){} -> ()=>{}
	*/
		$(()=>{
			$('#colorChange').click(()=>{
				//console.log($('#textPrint'));
				/*
					.css('css 속성명') -> 해당 css 속성의 값을 가지고 온다.
					.css('css 속성명', 'css 속성값') -> 해당 css 속성 부여.
					.css({
						css 속성명 : css 속성값,
						css 속성명 : css 속성값,
						css 속성명 : css 속성값
					})
				*/
				$('#textPrint').css('color','#f00');
			});
		});
	</script>

속성 조작 메서드2 - class

 

.addClass('클래스명') - 인수값을 class 속성에 추가한다.
.removeClass('클래스명') - 인수값에 해당되는 클래스를 제거한다.
- .hasClass('클래스명') - class 속성에 인수에 해당되는 값이 있는지 확인을 하고 결과를 true와 false로 반환한다.

<div id="divTarget">css 조작확인</div>
	<button type="button" id="classChangeBtn1">attr로 변환</button>
	<button type="button" id="classChangeBtn2">attr로 변환2</button>
	<button type="button" id="classChangeBtn3">class 메서드로 변환</button>
	<button type="button" id="classRemoveBtn1">class 메서드로 제거</button>
	<button type="button" id="classHasBtn1">class 메서드로 확인</button>

 

<script type="text/javascript">
	$(function(){
		var divTarget = $('#divTarget');
		$('#classChangeBtn1').click(function(){
			divTarget.attr('class','my-class01');
			
		});
		$('#classChangeBtn2').click(function(){
			// attr로 클래스 삽입이 기존에 있는 클래스로 변경된다.
			// 추가하기 위해서는 class 속성값을 가지고와 연산하여 재삽입을 해줘야 한다.
			divTarget.attr('class', divTarget.attr('class') +' my-class02');
		
		});
		$('#classChangeBtn3').click(function(){
			divTarget.addClass('my-class02');
		});
		$('#classRemoveBtn1').click(function(){
			divTarget.removeClass('my-class02');
		});
		$('#classHasBtn1').click(function(){
			console.log(divTarget.hasClass('my-class02'));
		});
	});
		
	</script>

 

클래스 메서드 사용 예시

<input type="text" class="my-input n-text">
	<button type="button" id="textCheck">확인</button>
<script type="text/javascript">
		$(function(){
			var myInput = $('.my-input');
			$('#textCheck').click(function(){
				if(myInput.hasClass('n-text')){
					myInput.removeClass('n-text').addClass('danger-text');
				}else{
					myInput.removeClass('danger-text').addClass('n-text');
				}
			});
		});
	
</script>

 

'41기 개발자과정' 카테고리의 다른 글

20211115 html5 설정  (0) 2021.11.15
20211115 ajax  (0) 2021.11.15
20211111 제이쿼리 01  (0) 2021.11.12
20211111 동적이벤트 바인딩  (0) 2021.11.11
20211105 ~ 20211110 팀프로젝트  (0) 2021.11.11
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG more
«   2025/04   »
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
글 보관함