选择之前的锚标记并使用 jQuery 添加一个类

发布于 2024-12-19 05:37:32 字数 442 浏览 4 评论 0 原文

基本上我有两个由 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 选择器非常昂贵,所以我想知道是否有更简单的方法来选择前一个锚节点,(同时忽略第二个)。

Basically I've got two anchor tags separated by a div.

<a class="foo"></a>

<div class="count">0</a>

<a class="bar"></a>

and I'm doing something like this:

       var addClass = $(this).parent().children('a:first-child').addClass('new');

It will then add it to the first anchor tag like so:

<a class="foo new"></a>

I know using the nth:child selector is pretty expensive, so I was wondering if there was an easier way to select that previous anchor node, (while ignoring the second one).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

土豪 2024-12-26 05:37:32

您可以这样做

$(this).parent().children('a:eq(0)').addClass('new');

了解有关 :eq() 的更多信息

或者,如果 < 之间没有元素code>

,您可以执行

$(this).prev('a');

了解更多.prev()

You could do this

$(this).parent().children('a:eq(0)').addClass('new');

Learn more about :eq()

Alternatively, if there are no elements between the <a> and the <div>, you could do

$(this).prev('a');

Learn more about .prev()

沒落の蓅哖 2024-12-26 05:37:32

我可能会将 prevAllfirst (或 eq(0),因为 first 只是调用 eq(0),但我发现 first 更具可读性):

$(this).prevAll("a").first().addClass("new");
// or
$(this).prevAll("a").eq(0).addClass("new");

prevAll 返回该元素之前的所有同级元素,按顺序从最接近的同级元素开始,当然还有 first / eq( 0) 将集合减少到第一个元素。

您可能会想将 :first 选择器与 prevAll 一起使用,以避免构建不必要的同级列表,但是 令我惊讶的是,事后使用first效果更好

I'd probably combine prevAll with first (or eq(0), since first just calls eq(0) — but I find first more readable):

$(this).prevAll("a").first().addClass("new");
// or
$(this).prevAll("a").eq(0).addClass("new");

prevAll returns all of the element's preceding siblings, in order starting with the closest sibling, and of course first / eq(0) reduces the set to the first element.

You might be tempted to use the :first selector with prevAll to avoid building up an unnecessary list of siblings, but to my surprise it works better to use first after-the-fact.

悸初 2024-12-26 05:37:32

怎么样:

$(this).siblings('a').eq(0).addClass(0);

实际上,如果你的结构像你的例子一样简单,你可以做一个简单的:

$(this).prev().addClass(0);

jQuery的 遍历方法为您提供了多种到达任何给定目的地的方法。

How about:

$(this).siblings('a').eq(0).addClass(0);

Actually, if your structure is as simple as in your example, you can just do a simple:

$(this).prev().addClass(0);

jQuery's traversal methods give you lots of ways to get to any given destination.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文