2009-10-08 4 views
0

내가 이것을 가지고 있다고 가정 해보자 :Javery는 Jquery를 사용합니다! 루핑 및 인쇄 가치

<div id="apple" class="fruit"></div> 
<div id="orange" class="fruit"></div> 
<div id="grape" class="fruit"></div> 
<div id="pear" class="fruit"></div> 

어떻게 "fruit"클래스의 모든 과일 ID를 반복하고 출력 할 수있는 자바 스크립트 함수를 작성합니까? JQuery 사용하기.

답변

5
$('div.fruit').each(function(){ 
//will loop through all divs with the class fruit. 
$(this).attr('id'); //will give you the id of the current div 
}); 
+0

<div class="fruit"> 인과 그 기능, this.attr ("ID") –

+0

this.attr ("ID") 내에서 수용 할 다음은 적합한 사용! – TIMEX

+2

this.id도 작동해야하나요? – Colin

2

쉼표로 구분 된 목록으로 인쇄됩니다 (ids는 ID 배열입니다).

var ids = $.map($('div.fruit'), function(e) { 
    return e.id; 
}); 
document.write(ids.join(',')); 

Working Demo - 출력을 볼 수있는 출력 탭을 클릭합니다.

이없는 id

var ids = $.map($('div.fruit'), function(e) { 
    return e.id? e.id : null; 
}); 
+0

콜백 함수의 첫 번째 인수는 리스트의 요소는'this.id'를 대신 사용하십시오; DOM 요소가 될 콜백 함수에 두 번째 인수를 사용하십시오. 또는'$ (this) .attr ('id')'를 사용하십시오. –

+0

@ 브렛 - 틀렸어. http://docs.jquery.com/Utilities/jQuery.map 설명서를 읽으십시오. http://jsbin.com에서 시험해보십시오 –

+0

두 번째 인수 (아직 주어지지 않았습니다)는 색인 –