본문 바로가기

jQ

jQ_2강

  Selector(선택기, 선택자)

태그명, id 속성값(#), class 속성값(.), *(모든 요소 선택), this(이벤트 발생 요소)

이때 this는 버튼일 경우 클릭한 버튼 자체가 되며, 문자열로 넣지 않는다.

 

조합 선택기)

  • 태그명.클래스값 => ex) $("p.cls") : <p class="cls">
  • 태그명.first => ex) $("p:first") : 여러 p 요소 중 첫 번째

기타 선택기)

  • [속성] => ex) $("[href]") : href 속성이 있는 <a>들
  • 태그[속성='값'] => ex) $("a[target='_blank'") : <a target='_blank'>인 요소들
  • 버튼 타입의 input 태그 : $(":button")
  • $("tr:even") : 테이블 짝수 행
  • $("tr:odd") : 테이블 홀수 행
  • CSS의 선택기와 동일 : $("p:nth-child(3)") 등

참고) jQuery 3.X 버전의 버그(bug)

모든 요소를 선택해 show를 실행할 경우 ( => $("*").show() ) Js 코드도 페이지에 보이는 버그가 존재한다. 이를 해결하는 방법으로는 이러한 버그가 없는 2.X 버전을 다운받는 것이 좋다.

jQuery 사이트 > blog 메뉴 > 2.1 검색 > 2.1.4 Released 게시글로 이동 후 다운로드한다.

  이벤트 처리

  • click() : 요소를 클릭할 때
  • dblclick() : 요소를 더블 클릭할 때
  • mouseenter() : 요소 내부로 마우스 포인터가 들어갔을 경우(hover)
  • mouseleave() : 요소 밖으로 마으스 포인터가 나갈 경우
  • mousedown() : 마우스 버튼이 눌릴 경우
  • mouseup() : 눌린 마우스 버튼에서 손을 뗀 경우
  • hover() : mouseenter()와 같음
  • focus() : input 태그가 포커스를 가진 경우
  • blur() : input 태그의 포커스가 해제된 경우
  • on() : 요소에 이벤트를 추가(동적, 복합 이벤트 처리)

예제)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Event</title>
    <style>
        생략
    </style>
</head>
<body>
<p>클릭하면 글자 색상이 바뀌어요~!</p>
<p>클릭하면 글자 색상이 바뀌어요~!</p>
<p>클릭하면 글자 색상이 바뀌어요~!</p>
<p>클릭하면 글자 색상이 바뀌어요~!</p>
<div id="mousezone">마우스 존</div>
<div id="overzone">H 오버 존</div>
아이디: <input type="text" name="userid">
<br>
비밀번호: <input type="password" name="userpass">
</body>
<script src="js/jquery-3.6.1.min.js"></script>
<script>
    $("p").click(function() {
        $(this).css("color", "pink");
    });

    $("p").dblclick(function (){
        $(this).css("color", "hotpink");
    });

    $("#mousezone").mouseenter(function (){
        $(this).text("마우스가 들어왔다!!!");
        $(this).css("backgroundColor", "purple");
    });

    $("#mousezone").mouseleave(function (){
        $(this).text("마우스가 나갔다...");
        $(this).css("backgroundColor", "violet");
    });

    $("#mousezone").mousedown(function (){
        $(this).text("마우스 버튼 눌림!");
        $(this).css("color", "gold");
    });

    $("#mousezone").mouseup(function (){
        $(this).text("마우스 버튼 뗌!");
        $(this).css("color", "black");
    });

    $("#overzone").hover(function (){
        $(this).text("마우스가 들어왔다~~");
        $(this).css("backgroundColor", "blue");
    }, function (){
        $(this).text("마우스가 나갔다...~");
        $(this).css("backgroundColor", "skyblue");
    });

    $("input").focus(function (){
        $(this).css("backgroundColor", "#cccccc");
    });

    $("input").blur(function (){
        $(this).css("backgroundColor", "#ffffff");
    });
</script>
</html>

'jQ' 카테고리의 다른 글

jQ_5강  (0) 2022.10.30
jQ_4강  (0) 2022.10.30
jQ_3강  (0) 2022.10.29
jQ_1강  (0) 2022.10.27
jQ_0강  (0) 2022.10.25