jquery - 从 jQuery 中的匹配元素获取父元素

标签 jquery

我有一个疑问:

这是查找比匹配元素高两级的父元素的好习惯吗? html 结构如下所示:

<div class="cli_visitas left cli_bar hand" title="Control de las visitas del cliente">              
    <a href="/fidelizacion/visitas/nueva/id/<?php echo $cliente->getId();?>">
        <span id="cli_visitas<?php echo $cliente->getId();?>" class="cli_bar_msg">La última visita <span class="lastvisit" ><?php echo $this->estados()->getUltimaVisita($cliente->getId());?></span></span>
   </a>
</div>

'.lastvisit' 触发事件,我想获取父级 '.cli_visitas' div 我正在这样做:

$(this).parent().parent().parent().css({boxShadow : '0px 0px 5px #DF0101',backgroundColor:'#F89494'});

这是一个好的做法吗?我不想使用 .parents() 方法并迭代每个元素并找到我想直接访问它的父元素。 我尝试过 .get() 但我认为这种方法不适合我的提议 还有其他方法吗?

非常感谢。 问候。

最佳答案

您可以使用以下两种替代方法来完成此操作。

一个

$(this).closest('div.cli_visitas')

第二

$(this).parents('div.cli_visitas')
$(this).parents('div.cli_visitas').eq(1)

Franc 在评论中添加了很酷的解释

As an additional note, for OP's benefit, on how those differ .closest() will get the first element that matches the selector traversing up through its ancestors in the DOM tree. It will stop as soon as it found a match .parents() on the other hand will get all ancestors matching the specified selector, or all parent ancestors if no selector was specified. Therefore if you have a very large nested DOM tree, closest() will be more efficient. Off course, if you need to access the nth-ancestor in the match parents().eq() would probably be more appropriate.

关于jquery - 从 jQuery 中的匹配元素获取父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16298527/

相关文章:

javascript - 添加组织的工作时间

javascript - 如何使用 jQuery 在鼠标悬停时制作简单的淡入淡出效果或慢速动画

javascript - 我在哪里可以下载 jquery cookie 插件?

javascript - 调用 $find 是一个相对昂贵的操作吗?

jQuery - 链接事件来执行函数

javascript - 我如何实现自动建议,如浏览器搜索字段(不是自动完成下拉菜单)?

javascript - 如何延迟 Jquery UIBlock 插件?

javascript - 通过 jquery 获取特定国家/地区的当前时间

javascript - jQuery Accordion 菜单 : scroll to active menu item

javascript - jQuery:检查复选框是否被选中