JQuery_선택자

개발중·2021년 9월 24일
0

자바스크립트

목록 보기
1/3

$("태그") : 해당 태그 전체를 선택

$("#아이디") 혹은 $("태그#아이디") : 해당 아이디 혹은 태그 중 해당 아이디를 가진 태그 선택

$(".클래스명") 혹은 $("태그.클래스명") : 해당 클래스 혹은 태그 중 해당 클래스를 가진 태그 선택

$("#아이디명, #아이디명, #아이디명") : 해당 아이디를 통해 태그를 그룹화하여 선택

<script type="text/javascript">
	$(function(){ // load function
		$("div:first").click(function(){ // div 태그 중 첫 번째 태그만 선택
			//alert($(this).html()+' '+this.innerHTML); html 확인하는 법
			$(this).html('한 번 클릭');
			alert('이벤트 클릭');
			$(this).unbind(); // 한 태그 당 한 번 눌리면 그 다음부터는 눌러도 바인드가 적용되지 않게 함
		
		});

		$("div:last").one('click', function(){ //div 태그 중 마지막 태그에만 적용 / one이라는 메소드는 한 번만 적용된다는 뜻
			//alert($(this).html()+' '+this.innerHTML); 같은 기능
			$(this).html('마지막 클릭');
			alert('이벤트 클릭');
		});
		
	});
    $("p").click(function(){
			$(this).html(function(index, html){
				return '<b>'+html+'</b>'; // p태그 안에 <b> 태그를 추가
			});
		});
		$("p").dblclick(function(){
			$(this).html(function(index, html){
				return html+'*'; // p태그 안에 <b> 태그를 추가
			});
		});
		setInterval(function(){
			$("p").last().trigger('dblclick');
		}, 1000); // 1초마다 더블 클릭 이벤트가 트리거를 통해 실행된다
	});
</script>

div를 클릭하면 img 태그가 전체 선택된다.
span을 클릭하면 img 태그가 하나씩 선택된다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
	$(function(){
		var i=0; // 하나씩 사라지게 하기 위해 지역 변수를 사용
		$("div").click(function(){ //div를 클릭하면 익명 펑션이 실행
			$("img").attr("id", function(i, id){ // i 인덱스 값을, id는 img 태그마다의 id 값을 가리킨다
				//alert(i+' '+id);
			}).each(function(i2, dom){ // 
				//alert(i2+' '+dom); // i2는 위와 같이 인덱스 값을, dom은 img 태그를 가리킨다
				if($(this).css("display")!="none"){ // if문을 통해 해당 img 태그의 css("display") 상태에 따라 속성값을 줌
				$(this).css("display", "none"); // $(this)는 현재 img 태그들을 가리킴
				}else{
					$(this).css("display", "inline");
				}
			});
		});
		
		$("span").click(function(){ // span을 누를 때마다 img 태그가 하나씩 display가 none이 되도록 설정
			if($("#img"+i).css("display")!="none"){
				$("#img"+i).css("display", "none");
			}else{
				$("#img"+i).css("display", "inline");
			}
			if(i>=3){
				i=0; // i의 값이 현재 img id의 태그 크기보다 커지면 0으로 초기화해 준다.
			}else{
				i++; // 값을 올려 주어야 다음이 진행된다.
			}
		});
	});
</script>
</head>
<body>
<div>전체</div>
<span>하나씩</span>
<br><br><br>
<img src="/web/cook-img/당근.png" id="img0" width=100px>
<img src="/web/cook-img/청포도.png" id="img1" width=100px>
<img src="/web/cook-img/자두.png" id="img2" width=100px>
<img src="/web/cook-img/감자.png" id="img3" width=100px>


</body>
</html>
profile
공부한 것 정리하는 개발 입문자

0개의 댓글

관련 채용 정보