jQuery 祖先

"祖先"指当前元素上面的所有层级:父级、祖父级、曾祖父级……jQuery 提供 parent()、parents()、parentsUntil()、closest() 四个方法做向上遍历。

演示用的层级结构:

<div class="great-grand">        <!-- 高祖父 -->
    <div class="grand">          <!-- 祖父 -->
        <ul class="parent">      <!-- 父级 -->
            <li id="me">我自己</li>
        </ul>
    </div>
</div>

parent():只取直接父级

parent() 返回直接父元素,只向上跳一级:

var p = $("#me").parent();
console.log(p.attr("class")); // 输出:parent

效果:拿到的是 ul.parent,再上面的 grand 不会出现。

parents():取全部祖先

parents() 一路向上,返回所有祖先元素的集合(不含自己、含 html 根):

$("#me").parents().each(function () {
    console.log($(this).attr("class"));
});
// 输出:parent、grand、great-grand

也可以传选择器过滤,只取符合条件的祖先:

console.log($("#me").parents(".grand").length); // 输出:1

parent() 与 parents() 的区别

方法返回范围典型用途
parent()仅直接父级(1 个或 0 个)找上一层的容器
parents()所有祖先(可传选择器过滤)判断元素属于哪个区域

简单说:parent 只看"爸爸",parents 看"爸爸+爷爷+太爷爷……"。

parentsUntil():遇到指定祖先即停

parentsUntil(选择器) 从父级往上收集祖先,遇到选择器匹配的元素就停止(不含它):

$("#me").parentsUntil(".great-grand").each(function () {
    console.log($(this).attr("class"));
});
// 输出:parent、grand(遇到 .great-grand 就停,它本身不被包含)

适合找"夹在两层之间的所有祖先"。

closest():从自身开始向上找

closest(选择器) 从元素自身开始逐级向上,返回第一个匹配的元素:

console.log($("#me").closest("ul").attr("class"));  // 输出:parent
console.log($("#me").closest("div").attr("class")); // 输出:grand(自身是 li 不匹配,向上第一层 div)

与 parents() 的关键区别:closest 包含自身起点,且只返回第一个命中者;parents 不含自身、返回全部。

closest() 的典型场景:事件委托定位

点击任意 li 时,用 closest() 找到它所在的面板:

$("li").click(function () {
    var panel = $(this).closest("div.grand"); // 无论点哪个 li 都能定位到 .grand
    console.log(panel.attr("class"));         // 输出:grand
});
// 效果:点击 #me 时弹出所在 .grand 容器的类名

小结

向上遍历四方法:parent() 只看爸爸、parents() 收齐所有祖先、parentsUntil() 收"到边界为止"的祖先、closest() 从自己开始找最近匹配者。事件处理里 closest() 是最常用的定位利器。

笔记加载中…