gpt4 book ai didi

javascript - JQUERY 在多个无序列表中选择第 n 个列表元素

转载 作者:行者123 更新时间:2023-11-28 08:34:29 24 4
gpt4 key购买 nike

不幸的是,这不能用纯 css 来完成,因为 nth-of-type 只选择与元素的父元素 (w3schools) 的关系。所以我正在寻找适用于多个列表的 jquery 替代方案。

HTML:

<div class="container" id="videos">
<ul class="thumbnails">
<li class="tn">
<img class="tn-img" src="img/thumbnails/placeholder.jpg" />
</li>
<li class="tn">
<img class="tn-img" src="img/thumbnails/placeholder.jpg" />
</li>
<li class="tn">
<img class="tn-img" src="img/thumbnails/placeholder.jpg" />
</li>
<li class="tn">
<img class="tn-img" src="img/thumbnails/placeholder.jpg" />
</li>
</ul>
<ul class="thumbnails">
<li class="tn">
<img class="tn-img" src="img/thumbnails/placeholder.jpg" />
</li>
<li class="tn">
<img class="tn-img" src="img/thumbnails/placeholder.jpg" />
</li>
</ul>
<ul class="thumbnails">
<li class="tn">
<img class="tn-img" src="img/thumbnails/placeholder.jpg" />
</li>
<li class="tn">
<img class="tn-img" src="img/thumbnails/placeholder.jpg" />
</li>
<li class="tn">
<img class="tn-img" src="img/thumbnails/placeholder.jpg" />
</li>
<li class="tn">
<img class="tn-img" src="img/thumbnails/placeholder.jpg" />
</li>
<li class="tn">
<img class="tn-img" src="img/thumbnails/placeholder.jpg" />
</li>
</ul>
</div>

JQUERY

$( "#videos li:nth-of-type(5n+1) img" ).css( "margin-left" , "0px");

此代码仍在选择 :nth-of-type(5n+1) 与其父级(无序列表)相关。我知道是因为每个 ul 中的第一个列表项都被选中了。我需要在每个无序列表中选择第 5 个列表项,而不管它的父项。

最佳答案

var items = $('#videos li'),
counter = 0, // first element, counting starts at zero
step = 5,
item = null;

while((item = items.eq(counter)).length) {
item.addClass('special'); // or do whatever else with it
counter += step;
}

http://jsfiddle.net/1573ahug/


编辑:或者,通过一个很好的 ol' for 循环(这样我们就不必经常调用 .length 来查看是否还有元素):

var items = $('#videos li'),
start = 0, // first element, counting starts at zero
step = 5;

for(var i=start, l=items.length; i<l; i+=step) {
items.eq(i).addClass('special');
}

http://jsfiddle.net/1573ahug/1/

关于javascript - JQUERY 在多个无序列表中选择第 n 个列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28117363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com