[jQuery] HTML 속성 제어

형이·2023년 8월 17일

jQuery

목록 보기
4/14
post-thumbnail

📝 jQuery

🖥️ 1. HTML 속성 제어

1-1. this

  • 이벤트에 의해서 실행된 함수 영역 안에서는 특수 키워드 this를 사용할 수 있다.
  • 자기자신

1-2. index()

  • 특정 객체에 대하여 index() 함수의 리턴값을 사용하면 자신이 속한 부모 태그 안에서 태그 종류의 구분 없이 자신이 몇 번째 요소인지를 알 수 있다.
  • 0부터 카운트한다.
  • $(this).index() -> 0, 1, 2

📝 예제

EX)

<head>
	...
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/
    		3.7.0/jquery.min.js"></script>
</head>
<body>
    <div>
        <button type="button" id="single">클릭하세요</button>
    </div>
    <hr/>
    <div>
        <button type="button" class="multi">button0(0번 클릭됨)</button>
        <button type="button" class="multi">button0(0번 클릭됨)</button>
        <button type="button" class="multi">button0(0번 클릭됨)</button>
    </div>

    <script>
        let counter = {single : 0, multi : [0, 0, 0]};
        $("#single").click(function(){
            counter.single++;
            $(this).html(counter.single + "번 클릭하셨습니다.");
        });
        $(".multi").click(function(){
            // 첫 번째 버튼 클릭 -> button0(1번 클릭됨)
            // 두 번째 버튼 클릭 -> button1(1번 클릭됨)
            let idx =  $(this).index();
            // console.log(idx);    값 확인하고 넘어가기!
            counter.multi[idx]++;
            $(this).html("button" + idx + "(" + counter.multi[idx] + "번 클릭됨)");
        });
    </script>
</body>

0개의 댓글