2013-05-23 2 views
3

안녕하세요, topmenu 요소의 각 항목의 너비를 읽고 항목의 너비를 추가하고 변수에 할당하려고합니다. 이 코드의 문제가 무엇인지 경고 에서 내가 NaN이 무엇입니까이 코드를 실행할 때 :

$(document).ready(function(){ 
    $('.topmenu').each(function(menu){ 
     var btext = $(this).find('.baritem').width(); 
     alert(btext); 
     var itemswidth = +itemswidth+btext; 
     alert(itemswidth); 
     //var width = getTextWidth(btext,"arial","40"); 
     //alert(width);  
    }); 
}); 
+0

유 수 html 코드를 보여주세요 – PSR

+3

'undefined + number = = NaN' ?? – elclanrs

답변

11

이 줄을

var itemswidth = +itemswidth+btext; 

는 숫자로 undefined를 추가합니다. 그러면 NaN이됩니다. 플로리안

$(document).ready(function(){ 
    var itemswidth = 0; 
    $('.topmenu').each(function(){ 
    var btext = $(this).find('.baritem').width(); 
    itemswidth += btext; 
    console.log(itemswidth); // better than alert 
    }); 
}); 

그리고 위해 : 당신은 루프에 들어가기 전에 0itemswidth를 초기화해야

$(document).ready(function(){ 
    var itemswidth = $('.topmenu .baritem').get().reduce(function(t,e){ 
     return t+$(e).width() 
    }, 0); 
    console.log(itemswidth); 
}); 
+0

나는'reduce'을 원합니다 : ( –

+0

@FlorianMargaine Happy now? –

0

당신은 쉽게 그것을 할 수 :

var reduce=Array.prototype.reduce; 
var completeWidth=reduce.call($("div"), function(sum, elem){ 
    sum+=$(elem).width(); 
    return sum; 
}, 0); 

http://jsfiddle.net/DSUHG/

+1

브라우저 호환성에 대한 언급은 플러스가 될 것입니다 :-) 그리고 원래의 예를 따르면 더 좋을 것입니다. –

관련 문제