반응형
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();
등등.
보다:
- http://api.jquery.com/first-selector/
- http://api.jquery.com/not-selector/
- http://api.jquery.com/gt-selector/
- https://api.jquery.com/slice/
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>
.child
모든 그룹의 모든 요소 를 숨기고 싶습니다 . 따라서 다음을.child
제외한 모든 요소 를 숨기므로 도움이되지 않습니다visible#1
.$('.child:not(:first)').hide();
솔루션 (이 확장 된 경우)은 다음과 같습니다.
$('.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
반응형
'Programing' 카테고리의 다른 글
if와 foreach에서 벗어나 다 (0) | 2020.03.30 |
---|---|
SSH 비밀번호를 확인 / 확인 / 테스트 / 확인하는 방법은 무엇입니까? (0) | 2020.03.30 |
개인 및 보호 회원 : C ++ (0) | 2020.03.30 |
Eclipse에서 Tomcat 7 빈 서버 이름 추가 (0) | 2020.03.30 |
Visual Studio Code에서 여러 줄을 주석 처리하는 방법은 무엇입니까? (0) | 2020.03.30 |