2015-04-28 25 views
0

$(this).parent().parent().parent()部分爲我們提供了一個<tbody>元素,它恰好有不止一個tr兒童的聲明jQuery length屬性:如果有多個匹配元素,將返回哪個元素的長度?

var length = $(this).parent().parent().parent().children('tr').length; 

那麼哪tr其中childrentbody返回$(this).parent().parent().parent()是這個特殊的tr其長度將由.length屬性返回?

............................................

documentation of the length property

說明:在 jQuery對象元素數。

我把它理解爲:在「jQuery對象」這裏是一個tr元素這是一個孩子通過$(this).parent().parent().parent()返回tbody在此jQuery對象「元素」的數量爲trtd的數量。所以這裏的.length屬性會返回trtd的數目,對吧?

但在給定的here(我複製下列供參考代碼)的例子中,語句

var n = $("div").length; 

分配ndiv S IN的body數。 但是,它不應該包含div的/ direct子元素的數量嗎?

。如果不同的div s有不同的長度,哪個divlength將被返回?

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8"> 
    <title>length demo</title> 
    <style> 
    body { 
    cursor: pointer; 
    } 
    div { 
    width: 50px; 
    height: 30px; 
    margin: 5px; 
    float: left; 
    background: green; 
    } 
    span { 
    color: red; 
    } 
    </style> 
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script> 
</head> 
<body> 
    <span></span> 
    <div></div> 
<script> 
$(document.body) 
    .click(function() { 
    $(document.body).append($("<div>")); 
    var n = $("div").length; 
    $("span").text("There are " + n + " divs." + 
     "Click to add more."); 
    }) 
    // Trigger the click to start 
    .trigger("click"); 
</script> 

</body> 
</html> 
+1

'length' *不*找到*內容長度*,發現*尺寸(數量)的對象*。你很複雜。 length屬性返回前一個對象中匹配元素列表的**大小**。這就對了!爲了計算div的子元素的長度/大小,需要使用$('div')。children()。length()'。 –

+0

@ShaunakD「返回前一個對象中匹配元素列表的大小」 - 謝謝你,我想我現在明白了。 – Solace

回答

1

考慮jQuery的對象length並不意味着一個特定的對象物的內部的內容長度。

length返回匹配元素的大小/數量。

$(this).parent().parent().parent().children('tr') . length 
|_______________________________________________|  |____| 
         |preceding object    |Size of the preceding list 

所以,如果<tbody>有4 <tr>秒 - 長度將返回4.

相關問題