jQuery는 먼저 제외하고 모두 선택 번째 요소를 제외한

jQuery에서 선택기를 사용하여 첫 번째 요소를 제외한 모든 요소에 액세스하려면 어떻게합니까? 따라서 다음 코드에서는 두 번째 및 세 번째 요소에만 액세스합니다. 수동으로 액세스 할 수는 있지만 가능한 많은 요소가있을 수 있습니다. 감사.

<div class='test'></div>
<div class='test'></div>
<div class='test'></div>



답변

$("div.test:not(:first)").hide();

또는:

$("div.test:not(:eq(0))").hide();

또는:

$("div.test").not(":eq(0)").hide();

또는:

$("div.test:gt(0)").hide();

또는 : (@Jordan Lev의 의견에 따라) :

$("div.test").slice(1).hide();

등등.

보다:


답변

jQuery 선택기가 오른쪽에서 왼쪽으로 평가되는 방식으로 인해 li:not(:first)해당 평가로 인해 읽기 속도가 느려집니다.

똑같이 빠르고 읽기 쉬운 솔루션은 기능 버전을 사용하는 것입니다 .not(":first").

예 :

$("li").not(":first").hide();

JSPerf : http://jsperf.com/fastest-way-to-select-all-expect-the-first-one/6

이것은 단지 몇 퍼센트 포인트보다 느리지 만 slice(1)“첫 번째 것을 제외한 모든 것을 원합니다”라고 읽을 수 있습니다.


답변

제 답변은 맨 위에 노출 된 사례에서 파생 된 확장 사례에 중점을 둡니다.

첫 번째 요소를 제외하고 하위 요소를 숨기려는 요소 그룹이 있다고 가정하십시오. 예로서:

<html>
  <div class='some-group'>
     <div class='child child-0'>visible#1</div>
     <div class='child child-1'>xx</div>
     <div class='child child-2'>yy</div>
  </div>
  <div class='some-group'>
     <div class='child child-0'>visible#2</div>
     <div class='child child-1'>aa</div>
     <div class='child child-2'>bb</div>
  </div>
</html>
  1. .child모든 그룹의 모든 요소 를 숨기고 싶습니다 . 따라서 다음을 .child제외한 모든 요소 를 숨기므로 도움이되지 않습니다 visible#1.

    $('.child:not(:first)').hide();
  2. 솔루션 (이 확장 된 경우)은 다음과 같습니다.

    $('.some-group').each(function(i,group){
        $(group).find('.child:not(:first)').hide();
    });

답변

$(document).ready(function(){

  $(".btn1").click(function(){
          $("div.test:not(:first)").hide();
  });

  $(".btn2").click(function(){
           $("div.test").show();
          $("div.test:not(:first):not(:last)").hide();
  });

  $(".btn3").click(function(){
          $("div.test").hide();
          $("div.test:not(:first):not(:last)").show();
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="btn1">Hide All except First</button>
<button class="btn2">Hide All except First & Last</button>
<button class="btn3">Hide First & Last</button>

<br/>

<div class='test'>First</div>
<div class='test'>Second</div>
<div class='test'>Third</div>
<div class='test'>Last</div>


답변