2012-12-29 2 views
2

나는 한 무리의 div를 가지고있다.자바에서 요소 n을 찾는 것

<div id="container"> 

    <div><a>One</a></div> 
    <div><a>Two</a></div> 
    <div><a>Three</a></div> 
    <div><a>Four</a></div> 

</div> 

은 내가 요소가 클릭 된 을 div에 무엇에, 자바 스크립트와 jQuery를 사용하여 찾을 수 있습니다.

소자 을 클릭 된 DIV에에 기초하여 정수 , (제 1, 제 2, 제 3 또는 제 4)을 반환해야한다.

답변

1

당신은 그것의 형제 자매들 사이의 위치를 ​​얻을 수 .index()를 사용하여 다음 a에서 div를 얻을 수 .parent()를 사용한다 ..

$('#container a').click(function(){ 
    var self = $(this), 
     clickedDiv = self.parent(), 
     index = clickedDiv.index(); 

    alert(index); // first is 0, second is 1 etc... 
}); 

이 그리 자세한 구문

일 것
$('#container a').click(function(){ 
    var index = $(this).parent().index(); 

    alert(index); // first is 0, second is 1 etc... 
}); 
+0

매력처럼 작동합니다. 감사합니다! –

3
var divs = $('#container').on('click', 'a', function() { 
    alert(divs.index(this.parentNode)); 
}).children('div'); 
+0

jQuery에 대한 다른 답변 Upvoting –

0

네이티브 JavaScript 구현 Array.prototype.forEach, .querySelectorAll.addEventListener을 사용합니다.

하나의 <a><div>

Array.prototype.forEach.call(// for each 
    document.querySelectorAll('#container a'), // <a> in #container 
    function (elm, idx, arr) { // get it's info (index etc.) then 
     elm.addEventListener('click', function() {console.log(idx);}, false); 
      // make clicking it log it's index 
    } 
); 

당 또는 <div>

Array.prototype.forEach.call(// for each 
    document.querySelectorAll('#container div'), // <div> in #container 
    function (elm, idx, arr) { // get it's info (index etc.) then 
     Array.prototype.forEach.call(// loop over each 
      elm.querySelectorAll('a'), // <a> in that <div> 
      function (a_elm, a_idx, a_arr) { // and 
       a_elm.addEventListener('click', function() {console.log(idx);}, false); 
        // make clicking it log the index of the <div> 
      } 
     ); 
    } 
); 

주 당 많은 <a>의가있는 경우 로그인 지수가 1에 대한 0에서 시작이 있다면.