반응형
jQuery로 컬렉션에서 클릭 한 요소의 인덱스 가져 오기
아래 코드에서 클릭 한 항목의 색인을 어떻게 얻습니까?
$('selector').click(function (event) {
// get index in collection of the clicked item ...
});
Firebug에서 나는 이것을 보았다 : jQuery151017197709735298827: 2
(나는 두 번째 요소를 클릭했다).
클릭 한 선택기의 색인을 경고합니다 (첫 번째는 0부터 시작).
$('selector').click(function(){
alert( $('selector').index(this) );
});
$('selector').click(function (event) {
alert($(this).index());
});
형제 자매
$(this).index()
요소가 형제 인 경우 클릭 한 요소의 색인을 가져 오는 데 사용할 수 있습니다.
<div id="container">
<a href="#" class="link">1</a>
<a href="#" class="link">2</a>
<a href="#" class="link">3</a>
<a href="#" class="link">4</a>
</div>
$('#container').on('click', 'a', function() {
console.log($(this).index());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="container">
<a href="#" class="link">1</a>
<a href="#" class="link">2</a>
<a href="#" class="link">3</a>
<a href="#" class="link">4</a>
</div>
형제가 아님
.index()
메서드에 인수가 전달되지 않으면 반환 값은 형제 요소에 상대적인 jQuery 객체 내 첫 번째 요소의 위치를 나타내는 정수 입니다.
선택기를 index(selector)
.
$(this).index(selector);
예:
<a>
클릭 한 요소 의 색인을 찾으십시오 .
<tr>
<td><a href="#" class="adwa">0001</a></td>
</tr>
<tr>
<td><a href="#" class="adwa">0002</a></td>
</tr>
<tr>
<td><a href="#" class="adwa">0003</a></td>
</tr>
<tr>
<td><a href="#" class="adwa">0004</a></td>
</tr>
$('#table').on('click', '.adwa', function() {
console.log($(this).index(".adwa"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="table">
<thead>
<tr>
<th>vendor id</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="#" class="adwa">0001</a></td>
</tr>
<tr>
<td><a href="#" class="adwa">0002</a></td>
</tr>
<tr>
<td><a href="#" class="adwa">0003</a></td>
</tr>
<tr>
<td><a href="#" class="adwa">0004</a></td>
</tr>
</tbody>
</table>
이렇게하세요 :-
$('ul li').on('click', function(e) {
alert($(this).index());
});
또는
$('ul li').click(function() {
alert($(this).index());
});
.bind (this)를 사용하는 경우 다음을 시도하십시오.
let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);
$(this.pagination).find("a").on('click', function(evt) {
let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);
this.goTo(index);
}.bind(this))
참고URL : https://stackoverflow.com/questions/5545283/get-index-of-clicked-element-in-collection-with-jquery
반응형
'code' 카테고리의 다른 글
Mac의 $ PATH에서 항목을 제거하는 방법 (0) | 2020.12.06 |
---|---|
AJAX 스타일 jQuery UI 탭에로드 된 jQuery UI 대화 상자 창 (0) | 2020.12.06 |
zlib 헤더는 어떻게 생겼습니까? (0) | 2020.12.06 |
C 면접-캐스팅 및 비교 (0) | 2020.12.06 |
Swift에서 Return 키를 누르면 텍스트 필드 간 전환 (0) | 2020.12.06 |