gpt4 book ai didi

javascript - jQuery - parent() 与 closest()

转载 作者:搜寻专家 更新时间:2023-11-01 05:11:36 24 4
gpt4 key购买 nike

假设我有以下标记:

<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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com