Programing

jQuery에서 인덱스로 요소 가져 오기

lottogame 2020. 8. 13. 07:38
반응형

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) 반환 : 요소

.eq(index) 반환 : jQuery


jQuery의 .eq()메서드를 사용 하여 특정 인덱스가있는 요소를 가져올 수 있습니다 .

$('ul li').eq(index).css({'background-color':'#343434'});

eq 방법 또는 선택기를 사용할 수 있습니다 .

$('ul').find('li').eq(index).css({'background-color':'#343434'});

CSS :nth-of-type의사 클래스를 사용하여 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

반응형