.closest()和.parents('selector')有什么区别?

编程入门 行业动态 更新时间:2024-10-23 14:27:53
本文介绍了.closest()和.parents('selector')有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这些之间有什么区别?一个比另一个更有效吗?我对为什么两者都存在感到困惑.说我有这个标记:

What's the difference between these? Is one more efficient than the other? I'm a little bit confused to why they both exist. Say I have this markup:

<table> <tr> <td>...</td> <td><span class='toggle'>Toggle</span></td> </tr> <tr> <td>...</td> <td><span class='toggle'>Toggle</span></td> </tr> <tr> <td>..</td> <td><span class='toggle'>Toggle</span></td> </tr> </table>

在<span>标记中,我可以使用 $(this).closest('tr');或$(this).parents('tr');来访问父级/最近的<tr>标记.

From the <span> tags I could use either $(this).closest('tr'); or $(this).parents('tr'); to access the parent/closest <tr> tag.

推荐答案

parent 返回直系亲代(一个用于调用者对象中的每个元素);如果父项与选择器不匹配,则什么都不做. closest 返回每个元素(可以是原始元素)的最接近祖先的匹配祖先.第三个类似的函数 parents 返回所有匹配的祖先(不包括元素本身).

parent returns the immediate parents (one for each element in the caller object) or nothing if the parent does not match the selector. closest returns the closest ancestor matching ancestor for each element (which can be the original element). The third similar function, parents, returns all matching ancestors (not including the element itself).

通常,如果您明智地选择选择器,则closest会比parent对重构HTML代码更具抵抗力.

Generally, closest is more resistant to refactoring the HTML code than parent, if you choose the selector sensibly.

更多推荐

.closest()和.parents('selector')有什么区别?

本文发布于:2023-10-14 22:25:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492396.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么区别   parents   closest   selector

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!