2013-07-29 4 views
0

섹션 내의 모든 div의 총 너비를 계산하려고합니다. .mainScroll 내에서 각 div의 너비를 계산하고이를 추가 한 다음 해당 내용의 합계에 해당 섹션의 너비를 설정하고 싶습니다. 다음은 내 HTML 마크 업입니다. 여기각 요소를 사용하여 jQuery를 사용하여 요소 내의 총 너비를 계산하십시오.

<section> 
     <div class="mainScroll"> 
      <div>some content</div> 
      <div>some content</div> 
      <div>some content</div> 
     </div> 
    </section> 
    <section> 
     <div class="mainScroll"> 
      <div>some content</div> 
      <div>some content</div> 
      <div>some content</div> 
     </div> 
    </section> 

그리고 지금까지 내 jQuery를 수 있습니다 :

var totalWidth = 0; 

$('section').each(function(){ 
    var select = $(this).find('.mainScroll div'); 
    select.each(function(index) { 
     totalWidth += parseInt($(this).outerWidth(true), 10); 
    }); 

    $(this).css({ 'width' : totalWidth}); 
    var totalWidth = 0; 

}); 

이가 NaN를 출력합니다. 이것을 어떻게 설정하여 각 섹션을 반복하고 그 섹션을 통해 개별 요소를 반복하고, 높이를 더한 다음 섹션이 그 정확한 높이를 갖도록 설정합니까?

+2

... 내가 있으리라 믿고있어'VAR은 = $ (이) .find ('mainScrolld의 사업부가.')을 선택합니다 (이'VAR = $을 선택 '해야) .find ('. mainScroll div');'? 거기에 여분의 'd'가 있습니다. ;) –

+0

예, 오타되었습니다, 지금 수정되었습니다 – JCHASE11

+0

for 루프에'console.log' 문을 삽입하는 것이 좋습니다. 내 생각 엔 당신의 숫자 중 일부가 문자열로 타이프되고''2 + 3 = NaN'이 될 것입니다. –

답변

0

모습이 fiddle 우선 들어

$('section').each(function(){ 
    var totalWidth = 0; 
    var select = $(this).find('.mainScroll div'); 
    select.each(function(index) { 
     totalWidth = +(totalWidth)+(+$(this).outerWidth(true)); 
    }); 

    //$(this).css({ 'width' : totalWidth}); 
    alert(+(totalWidth)); // total 
    var totalWidth = 0; 
}); 
관련 문제