○ this
- 선택한 요소 자신을 가리킴
- $(this) : jQuery에서 this객체 접근
<body>
<button>버튼1</button>
<button>버튼2</button>
<script>
$("body>button").click(function(){
//1)JavaScript
this.style.color="blue";
//2)jQuery
$(this).css("color", "blue");
})//click end
</script>
</body>
○ index
- index() : 해당 요소의 인덱스 가져오기
<body>
<button>버튼1</button>
<button>버튼2</button>
<script>
$("body>button").click(function(){
var idx=$(this).index();
alert(idx); //버튼1 클릭시 : 1
//버튼2 클릭시 : 2
})//click end
</script>
</body>
● PRACTICE 연습문제
Q) 각 버튼을 클릭했을 때, 해당 버튼의 정보를 <span>에 출력하기
- <span id="index"> : 해당 버튼 인덱스
- <span id="color"> : 해당 버튼 배경색
- <span id="text"> : 해당 버튼 글자
<head>
<meta charset="UTF-8">
<title>this_index</title>
<script src="jquery-3.6.0.min.js"></script>
<style>
#exBox {width: 400px; height: 300px;}
.btn {width: 120px; height: 50px; cursor: pointer;/*손모양커서*/}
#pinkBtn {background: hotpink;}
#blueBtn {background: deepskyblue;}
#greenBtn {background: greenyellow;}
</style>
</head>
<body>
<h3>this 연습</h3>
<div id="exBox">
<p>
<button id="pinkBtn" class="btn">멋진 핑크</button>
<button id="blueBtn" class="btn">쿨한 파랑</button>
<button id="greenBtn" class="btn">네온 녹색</button>
</p>
<dl>
<dt>클릭한 버튼정보</dt>
<dd>클릭한 버튼의 index : <span id="index">?</span></dd>
<dd>클릭한 버튼의 뒷배경색 : <span id="color">?</span></dd>
<dd>클릭한 버튼의 글자 : <span id="text">?</span></dd>
</dl>
</div>
<script>
$("#exBox .btn").click(function(){
var idx=$(this).index();
var color=$(this).css("background-color");
var txt =$(this).text();
$("#index").text(idx);
$("#color").text(color);
$("#text").text(txt);
})//click end
</script>
</body>
'Frontend > jQuery' 카테고리의 다른 글
08. jQuery, moment.js 오픈소스 (날짜 자동 생성, 아날로그 시계) (0) | 2022.06.07 |
---|---|
07. jQuery, 요소 생성 (append, prepend) (0) | 2022.06.07 |
05. jQuery, each반복문 (0) | 2022.06.07 |
04. jQuery, css() 함수 / prop()와 attr() 함수 (0) | 2022.06.03 |
03. jQuery, text()와 html() 함수 / jQuery Method Chaining (0) | 2022.06.03 |
댓글