2011-12-14 3 views
2

jQuery를 사용하여 테이블에 자식 (td ')이 가장 적은 요소 (tr)를 찾는 방법은 무엇입니까?어린이 수가 가장 적은 요소를 찾으십니까?

+0

AFAIK 'colspan' 또는'rowspan' 속성이있을 수있는'table'의 각'tr'에 동일한 수의'td'가 있어야합니다. 어떤 tr의 td가 최대'colspan'을 가지고 있는지 알고 싶습니까? – diEcho

답변

4
$(document).ready(function(){ 
    var tr = $('tr'); 
    tr.sort(function(a, b) { 
     return $(a).children('td').length - $(b).children('td').length; 
    }); 
    // $(tr).first() is your TR with fewest TDs 
}); 

JSFiddle Example

+0

+1 이것 역시 생각 해봐야합니다. : D 건배! –

+0

잘 작동합니다. 바이올린 예제를 추가했습니다. –

1

은 아마 사용자 정의의 jQuery 래퍼 방법으로 그 캡슐화 것입니다.

(function($) { 

    // blah with function name 
    $.fn.fewestChildren = function() { 

     var $this = $(this).filter('tr'), 
      bookmark = $this.eq(0) 
      ; 

     $this.not(bookmark).each(function() { 
      var $t = $(this); 
      if (bookmark.children('td').length > $t.children('td').length) { 
       bookmark = $t; 
      } 
     }); 

     return bookmark; 
    }; 

})(jQuery); 

난 그냥 사용할 수 있도록 같은 :

var foo = $('#mytable tr').fewestChildren(); 

정말 그래도 bookmark 변수를 사용하지 않고도 솔루션을보고 싶어요.

관련 문제