我有一个疑问:
这是查找比匹配元素高两级的父元素的好习惯吗? 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 matchparents().eq()
would probably be more appropriate.
关于jquery - 从 jQuery 中的匹配元素获取父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16298527/