简体   繁体   English

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

[英]Selecting previous anchor tag and adding a class to it with jQuery

Basically I've got two anchor tags separated by a div. 基本上,我有两个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). 我知道使用nth:child选择器非常昂贵,因此我想知道是否有一种更简单的方法来选择该先前的锚节点(而忽略第二个)。

You could do this 你可以这样做

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

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

Alternatively, if there are no elements between the <a> and the <div> , you could do 或者,如果<a><div>之间没有元素,则可以执行

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

Learn more about .prev() 了解有关.prev()的更多信息

I'd probably combine prevAll with first (or eq(0) , since first just calls eq(0) — but I find first more readable): 我可能会将prevAllfirst (或eq(0)结合起来,因为first只调用eq(0) ,但我发现first更具可读性):

$(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. prevAll按从最接近的同级开始的顺序返回元素的所有在前同级,当然first / eq(0)将集合减小为第一个元素。

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. 您可能会想将:first选择器与prevAll一起使用,以避免建立不必要的兄弟姐妹列表,但是令我惊讶的是,事后使用first 更好

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. jQuery的遍历方法为您提供了许多到达任何给定目标的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM