javascript - 元素出现但不是子元素的选择器

标签 javascript jquery html

我需要以某种方式为超出特定阈值的每个元素添加内联样式。为了以代码格式解释这一点,我的示例是这样的:

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-childnth-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/

相关文章:

HTML 5 音频、视频不工作 Safari 5.1 WinXP

javascript - html5 canvas文本中字体大小的有效粒度是多少?

javascript - 奇怪的 jQuery Ajax 问题

javascript - 我的 JavaScript 代码没有渲染我的谷歌地图

html - 从下拉菜单中选择选项时的事件处理

Javascript - 绑定(bind)到按键事件,除非用户处于文本输入状态

javascript - Chrome 和 IE 中的 Ctrl F/查找功能可修改布局

html - CSS - 使两个元素在小屏幕上重叠并在大屏幕上各自占据自己的宽度

javascript - Jquery foreach 循环

javascript - 可编辑的 javascript 和 Ajax