.closest()和.parents('selector')有什么区别? [英] What's the difference between .closest() and .parents('selector')?

查看:96
本文介绍了.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')有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆