JQuery nth-child选择器仅适用于:nth-​​child(1)

时间:2016-03-22 11:34:29

标签: javascript jquery

我试图在每第4个div之后插入一些东西,这是我的Jquery:

$( "<p>Test</p>" ).insertAfter(".top-car-img :nth-child(4n)");

但是,这不起作用。但是,如果我用4n替换1,那么它可以工作,每个元素都会获得p-tag。当我每4个元素尝试一次时,为什么它不起作用?

2 个答案:

答案 0 :(得分:1)

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="top-car-img" title="1" src=""/>
<img class="top-car-img" title="2" src=""/>
<img class="top-car-img" title="3" src=""/>
<img class="top-car-img" title="4" src=""/>
<img class="top-car-img" title="5" src=""/>
<img class="top-car-img" title="6" src=""/>
<img class="top-car-img" title="7" src=""/>
<img class="top-car-img" title="8" src=""/>
<img class="top-car-img" title="9" src=""/>
<img class="top-car-img" title="10" src=""/>
&#13;
> db.collection.find().forEach(function(doc) {
        var cat1Email = new Set(); 
        var cat2Email = new Set(); 

        doc.contacts.forEach(function(c){
            if (c.source === 'cat1'){
                // save the cat1 emails
                cat1Email.add(c.detail); 
                if (cat2Email.has(c.detail)){
                    // if there is same email from cat2, print this document 
                    return printjson(doc);
                }
            }else if(c.source === 'cat2'){
                // save cat2 email
                cat2Email.add(c.detail); 
                if (cat1Email.has(c.detail)){
                    // if there is same email from cat1, print this document
                    return printjson(doc)
                }
            }
        }); 
    })  
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

您必须删除元素和子元素之间的空格。

示例:

$( "<p>Test</p>" ).insertAfter(".top-car-img:nth-child(4n)");

Codepen: http://codepen.io/anon/pen/XdMLyq