我需要以某种方式为超出特定阈值的每个元素添加内联样式。为了以代码格式解释这一点,我的示例是这样的:
var listItems = $(".subitem");
listItems.each(function(index, value) {
console.log(listItems.length);
if (listItems.length > 5) {
// for every ".subitem" that is the 6th, 7th or however many but
// beyond the fifth, inject an inline style
}
}
我的第一个想法是 nth-child
和 nth-of-type
但都被淘汰了,因为标记大致如下:
<div>
<div class="subitem"></div>
</div>
<div>
<div class="subitem"></div>
</div>
<div>
<div class="subitem"></div>
</div>
使用此标记结构(无法更改),我如何才能最好地迭代 .subitem
的每个实例,并向超出限制的出现添加内联样式?
最佳答案
如此接近。如您所见,当您循环列表项时,索引会被传入。如果您看到索引超过 4(即在第 5 个元素之后),那么您可以使用 jquery 来应用您想要的样式。
var listItems = $(".subitem");
listItems.each(function(index, value) {
if (index > 4) {
// apply styling specific to elements 6 and beyond
}
}
关于javascript - 元素出现但不是子元素的选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50686193/