这些之间有什么区别?一个比另一个更有效吗?我对为什么两者都存在感到困惑.说我有这个标记:
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')有什么区别?
发布评论