2012-11-23 50 views
0

:last選擇器在某些情況下返回多個元素。 Here there is a jsfiddle嘗試它,因爲它很難相信!jQuery:最後選擇器奇數行爲

代碼一個失敗:

alert($(".child").find("span:last").length); // -> alerts 3 

jQuery documentation

說明:選擇最後一個匹配的元素。

注意:last通過過濾當前的jQuery集合並匹配其中的最後一個元素來選擇單個元素。

我錯過了什麼,或者這是一個錯誤?

+0

,如果你想找到他們最後,使用$( 「孩子 」)最後(「 跨度」)。 –

回答

3

當您使用.find():first:last,它搜索的第一和最後一個元素相對到使用$('.child')發現每個祖先元素

由於您有三個.child元素,因此您有三個元素可以在其中搜索span s。由於每個.child只有一個span,所以:last會在.find()的上下文中出現這三個中的每一個。然後.find()將它們收集在一起,因此您有三個span元素。

0

這是正常的,我想你需要的是:

alert($(".child:last").find("span:last").length); 

因爲否則只有「兒童」作爲選擇你將永遠進入第一。

0

解剖你的測試,我們有:

var matches = []; 
$('.child').each(function(){ 
    //get collection of all spans in the element 
    var collection = $('span',this); 

    //NOTE: There is only 1 span in collection at this point 

    //get last element 
    var match = collection.last(); 
    matches.push(match); 
}); 
alert(matches.length); //which is obviously 3