2012-10-20 2 views
-4

입니다 :
1. 사업부의 온 클릭의 인덱스를 : 클릭에하는 하나의 코드 다음 내가있어 가정하자이 요소

<div id="container"> 
<div onclick="func(this)"></div> 
... 
... 
<div onclick="func(this)"></div> 
</div> 

내가 얻을 수있는 기능 func 필요 -event가 호출되었습니다.
2. 컨테이너의 div 수입니다.

+1

6 downvotes 왜 아무 언급? 이 질문에 무엇이 잘못되었는지 궁금합니다. – Matthew

+2

사람들은 두 가지 질문의 영어, 특히 1 점을 구문 분석 할 수 없습니다. – bmargulies

+0

사실, 여기에있는 질문을 말하는 것이 어렵습니다. DOM 질문이라고 생각합니다 (태그를 추가했습니다). 조금 늦었지만 질문은 끝났으므로 @oneat, 어쩌면 당신은 당신이 무엇을 요구하고 있는지 명확히 할 수 있습니다. 나는 질문을 편집했지만 너무 많이 생각하고 싶지는 않습니다. – Matthew

답변

1

func은 첫 번째 인수로 을받는 것으로 가정하면 이전 형제를 순회하면서 몇 개가 왔는지를 계산하여 색인을 알아낼 수 있습니다.

총 카운트를 얻으려면 부모로부터 .children 카운트를 받으십시오. 당신이 .previousElementSibling이없는 오래된 브라우저를 지원해야하는 경우

function func(elem) { 
    var idx = 0; 
    var total = elem.parentNode.children.length; 
    // --------v----note the assignment! 
    while (elem = elem.previousElementSibling) { 
     idx++; 
    } 
    console.log("index:", idx, " of:", total); 
} 

, 당신은 nodeType 값이 다른 요소가 없음이 모든 가정 1.

function func(elem) { 
    var idx = 0; 
    var total = elem.parentNode.children.length; 
    // --------v----note the assignment! 
    while (elem = elem.previousSibling) { 
     if (elem.nodeType === 1) 
      idx++; 
    } 
    console.log("index:", idx, " of:", total); 
} 

것을 .previousSibling 테스트를 사용할 수 있습니다 카운트되어야하는 컨테이너에서. 다른 것들이 있다면, 카운트를 걸러 낼 필요가 있습니다.

1

이 코드는 당신이 필요로 할 것입니다 :

function func(el){ 
    // get the list of all element contained by the parent 
    var list = el.parentElement.children, i; 
    // get the index of the element 
    for (i = 0; i<list.length;i++){ 
     if (list[i] == el) break; 
    } 
    // logging index and total childrencount to console (F12) 
    console.log("children total: "+list.length); 
    console.log("# of element: "+ ++i); 
}​ 

Example