programing

jQuery 먼저를 제외한 모든 항목 선택

itmemos 2023. 5. 17. 22:30
반응형

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>

언급URL : https://stackoverflow.com/questions/2259393/jquery-select-all-except-first

반응형