반응형
jQuery에서 인덱스별 요소 가져오기
나는 순서가 없는 목록과 색인을 가지고 있습니다.li태그를 지정합니다.나는 그것을 받아야 합니다.li해당 인덱스를 사용하여 요소를 선택하고 배경색을 변경합니다.전체 목록을 반복하지 않고 이것이 가능합니까?제 말은, 이 기능을 달성할 수 있는 방법이 없을까요?
여기 제 코드가 있습니다. 작동할 것으로 믿습니다.
<script type="text/javascript">
var index = 3;
</script>
<ul>
<li>India</li>
<li>Indonesia</li>
<li>China</li>
<li>United States</li>
<li>United Kingdom</li>
</ul>
<script type="text/javascript">
// I want to change bgColor of selected li element
$('ul li')[index].css({'background-color':'#343434'});
// Or, I have seen a function in jQuery doc, which gives nothing to me
$('ul li').get(index).css({'background-color':'#343434'});
</script>
$(...)[index] // gives you the DOM element at index
$(...).get(index) // gives you the DOM element at index
$(...).eq(index) // gives you the jQuery object of element at index
DOM 개체에 없음css함수, 마지막...
$('ul li').eq(index).css({'background-color':'#343434'});
문서:
.get(index) 반환:요소
- 설명:jQuery 개체와 일치하는 DOM 요소를 검색합니다.
- 참조: https://api.jquery.com/get/
.eq(index) 반환: jQuery
- 설명:일치하는 요소 집합을 지정된 인덱스에 있는 요소 집합으로 줄입니다.
- 참조: https://api.jquery.com/eq/
jQuery의 방법을 사용하여 특정 인덱스를 가진 요소를 가져올 수 있습니다.
$('ul li').eq(index).css({'background-color':'#343434'});
eq 방법 또는 선택기를 사용할 수 있습니다.
$('ul').find('li').eq(index).css({'background-color':'#343434'});
CSS 유사 클래스를 사용하여 jQuery에서 인덱스로 요소를 가져오는 다른 방법이 있습니다.
<script>
// css selector that describes what you need:
// ul li:nth-of-type(3)
var selector = 'ul li:nth-of-type(' + index + ')';
$(selector).css({'background-color':'#343434'});
</script>
jQuery와 함께 사용하여 필요한 요소와 일치시킬 수 있는 다른 선택기가 있습니다.
jquery를 건너뛰고 CSS 스타일 태깅을 사용할 수 있습니다.
<ul>
<li>India</li>
<li>Indonesia</li>
<li style="background-color:#343434;">China</li>
<li>United States</li>
<li>United Kingdom</li>
</ul>
언급URL : https://stackoverflow.com/questions/9887534/get-an-element-by-index-in-jquery
반응형
'codememo' 카테고리의 다른 글
| 각도 - 동적으로 검증자 추가/제거 (0) | 2023.08.11 |
|---|---|
| macosx의 파이썬 위치 (0) | 2023.08.11 |
| jQuery 선택한 확인란의 값을 배열로 가져옵니다. (0) | 2023.08.11 |
| 오라클에서 문자열의 일부를 제거하는 방법 (0) | 2023.08.11 |
| 활동, 앱 호환 활동, 조각 활동 및 작업 표시줄 활동:어떤 것을 사용해야 합니까? (0) | 2023.08.11 |