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.