如何使用jQuery向每个元素添加类,除了每四个元素

How to add class, using jQuery, to every element except every fourth?

本文关键字:元素 四个 添加 jQuery 何使用      更新时间:2023-09-26

我有一个网站,我要把元素作为瓷砖在一行4。我想给每一个元素加上margin-left: 13px,除了每一行的第一个元素。谁能告诉我如何使用jQuery实现这个?

类似于

$('element:not(:nth-child(4n))')

演示:http://jsfiddle.net/G84B8/

示例:http://jsfiddle.net/ZVd6Y/

假设包装器行有一个row类…

和给定的HTML:

<div class="row">
    <p class="first">first row</p>
    <p>second row</p>
    <p>third row</p>
</div>
<div class="row">
    <p class="first">first row</p>
    <p>second row</p>
    <p>third row</p>
</div>

你想使用:

$(document).ready(function(){
    $('.row').children("p:not(.first)").addClass("extra-margin");
});
.extra-margin{
    margin-left: 13px;
}

您可以使用:not:nth-child()选择器。例子:

$('div:not(:nth-child(4n))').css('margin-left', '13px');

演示:http://jsfiddle.net/HsbUv/1/

试试这个:

var count = 0;
    $('.classname').each(function(){
        count++;
        if(count !== 4){
             $(this).css("margin-left", "13px");
        } else {
            count = 0;
        }
    });