2013-04-18 38 views
4

如何找到存在於div中的元素數?我也想打印列表元素目前在div。 我都試過,但它不工作..找到分區的長度

<!DOCTYPE html> 
<html> 
<head> 
<title> Div Length</title> 
<script type="text/javascript" src="js/jquery-1.6.2.min.js"> 

</script> 
<script> 
    $(function() 
    { 
    alert(' Elements are ' +$('#main').length); 

    } 
    ) 
</script> 
</head> 
<body> 

<div id="main"> 

<img src="images/thumb1.jpg"; height="30" width="30" /> 
<img src="images/thumb2.jpg"; height="30" width="30"/> 
<img src="images/thumb3.jpg"; height="30" width="30"/> 
<img src="images/thumb4.jpg"; height="30" width="30"/> 
<div id="main1"> 

</div> 

<div id="main2"> 

</div> 


</div> 
</body> 
</html> 

我需要找到長度,因爲我的動力從j查詢中添加的div元素所以在最後我要檢查什麼是一直的所有元素成功添加。

感謝,

+0

請參閱以下鏈接 http://stackoverflow.com/questions/250688/count-immediate-child-div-elements-using-jquery http://stackoverflow.com/questions/4291151/jquery-count-child-elements – 2013-04-18 05:34:05

回答

7

$("div#main").children().length

1

很多方法可以做到這一點。

A液:

根據你想算什麼:

$('#main div').length回報div的數量main DIV

$('#main img').length返回圖像的數量main DIV

3

如果你想處理已經動態添加的每個項目,你根本不需要獲得長度。相反,你可能只是什麼循環,雖然每一個這樣的

$('#main img').each(function(index){ 
    // Your code 
    console.log($(this).html()); 
});