2014-02-11 51 views
0

jQuery的濾波第n個孩子(N + X)沒有返回鑑於以下標記預期結果

<dl> 
    <dt>What are your hours?</dt> 
    <dd class="first">We are open 24/7.</dd> 
    <dt>What are your hours?</dt> 
    <dd class="second">We are open 24/7.</dd> 
    <dt>What are your hours?</dt> 
    <dd class="third">We are open 24/7.</dd> 
    <dt>What are your hours?</dt> 
    <dd class="fourth">We are open 24/7.</dd> 
    <dt>What are your hours?</dt> 
    <dd class="fifth">We are open 24/7.</dd> 
</dl> 

console.log($('dd').get()); 
//returns - [dd.first, dd.second, dd.third, dd.fourth, dd.fifth] 

使用此選擇器添加一個類「隱藏」的$('dd').filter(':nth-child(n+4)').addClass('hide');類適用於第二,第三,第四和第五。它是否不適用於第四和第五類?就好像$('dd')選擇器在count中包含了dt元素。爲什麼這樣呢?

<dl> 
    <dt>What are your hours?</dt> 
    <dd class="first">We are open 24/7.</dd> 
    <dt>What are your hours?</dt> 
    <dd class="second hide">We are open 24/7.</dd> 
    <dt>What are your hours?</dt> 
    <dd class="third hide">We are open 24/7.</dd> 
    <dt>What are your hours?</dt> 
    <dd class="fourth hide">We are open 24/7.</dd> 
    <dt>What are your hours?</dt> 
    <dd class="fifth hide">We are open 24/7.</dd> 
</dl> 

回答

1

號,第n個選擇器將只搜索子計數,其他過濾器不會應用到它 - 你的選擇將獲取所有dd元素,其大於3

你可以試試片的指數( )雖然

$('dd').slice(3).addClass('hide'); 

演示:Fiddle

+0

因此,釋義 - 第n個孩子計算父母的所有元素,這也包括dt指數。 ? – seasick

+1

@seasick是的! –

0

考慮以下標記:

<dl> 
    <dt>What are your hours?</dt> 
    <dd class="first">We are open 24/7.</dd> 
    <dt>What are your hours?</dt> 
    <dd class="second">We are open 24/7.</dd> 
    <dt>What are your hours?</dt> 
    <dd class="third">We are open 24/7.</dd> 
    <dt>What are your hours?</dt> 
    <dd class="fourth">We are open 24/7.</dd> 
    <dt>What are your hours?</dt> 
    <dd class="fifth">We are open 24/7.</dd> 
</dl> 

要選擇你需要使用下面的CSS-選擇的dt.fourthdt.fifth元素:

$("dd:nth-child(2n + 8)") // select dd element 
          // that is the 8th child of its parent 
          // and every 2nd sibling afterwards 

Demo here

應該:nth-​​child(n + 4)不應用該類到第四個和第五個? 就好像$('dd')選擇器在count中包含了dt元素。 這是爲什麼呢?

這就是nth-child的工作原理;它會檢查元素是否爲父元素的第n個子元素,而不是jQuery對象中的第n個元素。 dd:nth-child(n + 4)與其父代和下一代兄弟的第四個孩子的dd元素相匹配。