jQuery在此之后选择具有特定类的第一个元素 [英] jQuery select first element that has a certain class after this

查看:325
本文介绍了jQuery在此之后选择具有特定类的第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的小提琴: http://jsfiddle.net/jamesbrighton/wxWgG/4/

HTML:

<div>
    <p class="click">Click 1</p>
    <p>This should be ignored</p>
    <p>This should be ignored</p>
    <p>This should be ignored</p>
</div>

<div>
    <p class="target">Target 1</p>
</div>
<div>
    <p class="target">Target 2</p>
</div>


<div>
    <p class="click">Click 2</p>
    <p>This should be ignored</p>
    <p>This should be ignored</p>
    <p>This should be ignored</p>
</div>

<div>
    <p class="target">Target 3</p>
</div>
<div>
    <p class="target">Target 4</p>
</div>

jQuery:

$('.click').click(function() {
   $(this).nextAll('.target').css('color','red');
});​

我需要它,因此当您单击p.click时,下一个p.target变为红色.

I need it so when you click a p.click, the next p.target turns red.

因此,如果单击'Click 1',则'Target 1'变为红色.如果单击'Click 2',则'Target 3'变为红色.

So if you click on 'Click 1' then 'Target 1' turns red. If you click on 'Click 2' then 'Target 3' turns red.

.find一样,我也尝试过.closest,从jQuery文档看来,它似乎应该可以工作.从HTML中可以看到,.target不是.click的子级,以防万一.

As well as .find I've tried .closest and from the jQuery documentation it seems to me like it should work. As you can see from the HTML, .target is not a child of .click, in case that makes a difference.

推荐答案

这里是另一种方法,尽管我不知道在这种情况下性能.index()的表现如何.这也假定不存在两个连续的.click元素(或用不同的措词:两个.click元素之间始终至少有一个.target元素):

Here is another approach, although I don't know how performant .index() is in this case. This also assumes that there are never two consecutive .click elements (or phrased differently: There is always at least one .target element between two .click elements):

var $elements = $('.click, .target');

$('.click').click(function() {
   $elements.eq($elements.index(this) + 1).css('color','red');
});​

演示

之所以可行,是因为元素是按照在文档中显示的顺序选择的.

This works because the elements are selected in the order they appear in the document.

这篇关于jQuery在此之后选择具有特定类的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆