2014-10-09 2 views
1

를 얻기 위해 I DOM에 다음과 같은 구조를 가지고 :특정 하위 요소

을 :

<div class="parent"> 
    <div class="child0"></div> 
    <div class="child1"></div> 
    <div class="child2"></div> 
    <div class="child3"></div> 
    <div class="child4"></div> 
    <div class="child5"></div> 
      ... 
</div> 

내가 자바 스크립트에서 수행하려고하는 특정 요소를 보여이 같은 다른 사람을 숨기는 것입니다

showItems(0,3,'.parent'); // show child 0,1,2 

    function showItems(offset,limit,component) 
    { 
     $(component).children().hide(); 
     for(var i=offset;i<=(offset+limit);i++) 
     { 
      $(component+':nth-child('+i+')').show(); //!!! does not make them visible 
     } 

    } 

어떤 아이디어가 있습니까?

감사합니다.

답변

4

구성 요소와 : nth-child 사이에는 공백이 필요합니다. 왜냐하면 이제는 n 번째 자식 인 "parent"클래스가있는 요소를 선택하기 때문입니다.

1

당신은 그것을 쉽게와 같이, 대신 .eq() 방법을 사용한다 :

function showItems(offset,limit,component) 
{ 
    $(component).children().hide(); 
    for(var i=offset;i<=(offset+limit);i++) 
    { 
     $(component).children().eq(i).show(); //this will work! 
    } 

} 
1

그냥 당신이 선택 즉시 차일의 하나를 만들기 위해 '>'추가, Remco의에 의해 대답에 추가 .

그래서 한 가지 방법은 당신이 '>'기호를 배치하지 않는 경우이 경우

$(component+' > :nth-child('+i+')').show(); 

또는 더 나은

$(component+' > div:nth-child('+i+')').show(); 

, 또한, 자식 div의 내부 요소를 선택할 수 있습니다 쓸 수 있습니다 존재합니다.

+0

.children() 호출을 통해 직접 자식을 숨기고 있지만 우수한 점과 감독이 있으므로 실제로는 영향을주지 않아야합니다. –

+0

나는 두 번째가 첫 번째보다 낫다는 것을 보지 못한다. 모든 자식 요소는'div '요소이며, 그것이 알려진 경우 간단히': nth-child'대신'div : nth-child '를 사용하는 것이 사실은 효율성이 떨어집니다. 요소가'div'이고': nth-child'인지를 검사합니다. –

+0

이 경우에는 문제가되지는 않지만 부모 div에 더 많은 콘텐츠 또는 분리 기호 요소가있는 경우에는 도움이되지 않을까요? –

관련 문제