选择之前的锚标记并使用 jQuery 添加一个类
基本上我有两个由 div 分隔的锚标记。
<a class="foo"></a>
<div class="count">0</a>
<a class="bar"></a>
我正在做这样的事情:
var addClass = $(this).parent().children('a:first-child').addClass('new');
然后它将它添加到第一个锚标记,如下所示:
<a class="foo new"></a>
我知道使用 nth:child 选择器非常昂贵,所以我想知道是否有更简单的方法来选择前一个锚节点,(同时忽略第二个)。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以这样做
了解有关 :eq() 的更多信息
或者,如果 < 之间没有元素code> 和
,您可以执行
了解更多.prev()
You could do this
Learn more about :eq()
Alternatively, if there are no elements between the
<a>
and the<div>
, you could doLearn more about .prev()
我可能会将
prevAll
与first
(或eq(0)
,因为first
只是调用eq(0)
,但我发现first
更具可读性):prevAll
返回该元素之前的所有同级元素,按顺序从最接近的同级元素开始,当然还有first
/eq( 0)
将集合减少到第一个元素。您可能会想将
:first
选择器与prevAll
一起使用,以避免构建不必要的同级列表,但是 令我惊讶的是,事后使用first
效果更好。I'd probably combine
prevAll
withfirst
(oreq(0)
, sincefirst
just callseq(0)
— but I findfirst
more readable):prevAll
returns all of the element's preceding siblings, in order starting with the closest sibling, and of coursefirst
/eq(0)
reduces the set to the first element.You might be tempted to use the
:first
selector withprevAll
to avoid building up an unnecessary list of siblings, but to my surprise it works better to usefirst
after-the-fact.怎么样:
实际上,如果你的结构像你的例子一样简单,你可以做一个简单的:
jQuery的 遍历方法为您提供了多种到达任何给定目的地的方法。
How about:
Actually, if your structure is as simple as in your example, you can just do a simple:
jQuery's traversal methods give you lots of ways to get to any given destination.