jQuery:最后一个选择器奇怪的行为

时间:2012-11-23 12:47:17

标签: jquery jquery-selectors

在某些情况下,:last选择器会返回多个元素。 Here there is a jsfiddle尝试它,因为很难相信!

代码1失败:

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

jQuery documentation

  

描述:选择最后一个匹配的元素。

     

注意:last通过过滤当前选择单个元素   jQuery集合并匹配其中的最后一个元素。

我错过了什么或这是一个错误吗?

3 个答案:

答案 0 :(得分:3)

.find():first:last一起使用时,它会搜索相对于使用{{找到的每个祖先元素的第一个和最后一个元素 1}}。

由于您有三个$('.child')元素,因此您有三个元素可用于搜索.child。由于每个span只有一个.childspan会在:last的上下文中出现这三个中的每一个。然后.find()将它们全部收集在一起,因此您有三个.find()元素。

答案 1 :(得分:0)

这是正常的,我认为你需要的是:

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

因为只有“孩子”作为选择,你总是会输入第一个。

答案 2 :(得分: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