javascript - jQuery - parent() 与 closest()

标签 javascript jquery

假设我有以下标记:

<div class="parent">
    <div class="child">
        <div class="grand-child">

我想从 .grand-child 开始获取 .parent。我可以执行以下两项之一:

$('.grand-child').parent().parent();
$('.grand-child').closest('.parent');

总体而言,closest() 感觉是一种更好的方法,因为:

  1. 只有一个功能
  2. .grand-child.parent之间的其他div无关

具体来说,由于上面 #2 的优点,如果我要将标记更改为

<div class="parent">
    <div class="child">
        <div class="nanny">
            <div class="grand-child">

然后我需要添加一个额外的 parent()closest() 仍然可以正常工作。

那么您选择 parent()closest() 有什么原因吗?

最佳答案

你应该使用 $('.grand-child').closest('.parent'); 因为 .parent().parent() 是强基础的在你的 html 结构上,如果将来你在其中一个中添加另一个 div,那么你将使用 parent().parent()

得到错误的元素

假设你有这样的 html:

<div class="parent">
    <div class="child">
        <div class="grand-child-container">
             <div class="grand-child">

现在如果你使用 .parent().parent() 会发生什么,它会给你错误的元素,所以推荐的方法是使用 closest() 作为它好多了。

根据文档:

parent() gets the parent of each element in the current set of matched elements, optionally filtered by a selector.

closest() For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

差异:

如果您稍微向下滚动,您可以通过官方 jquery 站点看到这两者之间的差异。

关于这两者之间的区别,还有一些更好的答案:

parent vs closest

Difference between jQuery parent(), parents() and closest() functions

性能:

性能方面 closest() 也优于 parent(),你可以查看 Benchmark between closest() and parent()

关于javascript - jQuery - parent() 与 closest(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24983668/

相关文章:

javascript - 本地存储中的重复条目 - Javascript

jQuery 检查文档类型

javascript - 主干的客户端持久层?

javascript - DOM 节点清理在 d3 中如何工作?

javascript - 减去数组 - javascript

javascript - 暂时禁用javascript中的所有事件

javascript - 为什么 z 索引不起作用?

javascript - Javascript 中的 onLoad 函数

javascript - 使用 ID 和 JQUERY 将文本放入 DIV 元素中?

jquery - 更改 Lightbox 2 动画速度