javascript - 为什么第 nth-child 将样式添加到备用可见元素不起作用?

标签 javascript jquery html css

我正在努力为Alternate Visible Elements 添加样式。最初我想到了使用 nth-child(2n+1) 的想法,但显然它不起作用!。为了归结我的问题,下面是示例:

HTML:

<div class='hide find'>TEST</div>
<div class='hide find'>TEST</div> 
<div class='find'>TEST</div> 
<div class='hide find'>TEST</div> 
<div class='find'>TEST</div> 
<div class='hide find'>TEST</div> 
<div class='hide find'>TEST</div> 
<div class='find'>TEST</div> 
<div class='hide find'>TEST</div> 
<div class='find'>TEST</div>

CSS:

.hide{
    display:none;
}
.alternate{
    background-color:grey;
}

J查询:

$('.find:visible:nth-child(2n+1)').addClass('alternate');    //This is not working! Why?

我不确定失败的原因是什么。虽然,我对这个问题做了一些解决方法并创建了一个可以工作的函数,但如果可以使用上述方法解决问题,它会更顺利和更好。以下是我让它工作的解决方法:

function addAlternateStyle(){
var alt= true;
    $('.find:visible').each(function(){
        if(alt){
            alt=!alt;
            $(this).addClass('alternate');
        }
        else{
            alt=!alt;
        }
    });
}

感谢任何帮助。

最佳答案

你可以试试这个:-

$('.find:visible:even').addClass('alternate');

Demo

关于javascript - 为什么第 nth-child 将样式添加到备用可见元素不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31469989/

相关文章:

javascript - JS/JSX 函数总是返回 true,即使它是 false

javascript - 如何使用 javascript 在 Google map 上显示两个或多个标记

javascript - 使用构造函数弹跳动画?

html - 移动宽度时 Bootstrap 表单布局不正确

html - Bootstrap 3 - 容器在 IE8 上拉伸(stretch)

javascript - 哪些版本的 IE 使用标准事件模型?

javascript - 使用 Ajax 获取随机维基百科摘录

javascript - 加载更多功能或无限分页

javascript - 更改 .text() 内容并保留子 html

html - 响应式布局修改