code

jQuery로 컬렉션에서 클릭 한 요소의 인덱스 가져 오기

codestyles 2020. 12. 6. 21:34
반응형

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());
});

jsfiddle


형제 자매

$(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

반응형