2011-12-14 52 views
0

我有一個名爲'div.cloneFrame'的div,我使用jquery.clone來克隆它。它工作正常,我克隆所有我需要的,使用此功能:Jquery colone child count issue(nnth-child)

var needToClone = 4; 
    var totalImgs = 0; 
    for(i=0;i<needToClone;i++){ 
     $('div.cloneFrame').clone() 
     .removeClass('cloneFrame') 
     .appendTo('.frame-group').each(function(){ 
      var imgSrcLength = $(this).find('img'); 
      for(j=0;j<imgSrcLength.length;j++){ 
       totalImgs++; 
       $(imgSrcLength[j]).attr('src','imgs/outfits/'+totalImgs+'.jpg'); 
      } 
     }) 
    } 
    $('div.cloneFrame').remove(); 

後,我需要選擇克隆DIV,爲我使用第n個子功能

$('div.myframe:nth-child('+1+')').addClass('incoming').next().addClass('outgoing'); 

但不起作用。如果我使用這種方式:

$('div.myframe:nth-child('+3+')').addClass('incoming').next().addClass('outgoing'); 

它運作良好。爲什麼它需要在第n個孩子上掃2個數字?我身邊有什麼不對?

我的HTML:

<div class="frame-group"> 

      <div class="cloneFrame myframe"> 
       <div id="orange-frame" class="product-frame"> 
        <a class="purchase-btn" href="#">Purchase this item</a> 
        <img alt="women coat" src="imgs/yellow-coat.jpg"> 
       </div> 
       <div id="yellow-frame" class="product-frame"> 
        <a class="purchase-btn" href="#">Purchase this item</a> 
        <img alt="blue coat" src="imgs/coat-blue.jpg"> 
       </div> 
       <div id="brown-frame" class="product-frame"> 
        <a class="purchase-btn" href="#">Purchase this item</a> 
        <img alt="women shoe" src="imgs/women-shoe.jpg"> 
       </div> 
       <div id="green-frame" class="product-frame"> 
        <a class="purchase-btn" href="#">Purchase this item</a> 
        <img alt="women jean" src="imgs/jean.jpg"> 
       </div> 
      </div> 


      <span class="outfit-no">outfit no.<span>01</span></span> 
      <a class="buy-outfit" href="#">Buy outfit</a> 
     </div> 

,請訪問:http://jsbin.com/iquxaq/3

回答

1

從jQuery的:nth-child()選擇:

附:第n個孩子(N),所有的孩子都算,不管他們 是什麼,指定的元素只有在匹配 選擇器附加到僞類。利用:eq(n)只對附加到僞類的選擇器 進行計數,不限於任何其他元素的子元素,並且選擇第(n + 1)個元素(n是從0開始的)。

解決方案

不管我的測試,

  • $('div.myframe:nth-child(1)')嘗試看,如果div.myframe有第一個孩子,如果這個元素有類= 「myframe」。在這種情況下,它是<span class="outfit-no">outfit no.<span>01</span></span>,所以沒有任何東西被抓住。

  • 之後,對於$('div.myframe:nth-child(2)')試圖抓住第二個孩子,但它仍然不是一個.myframe,它是<a class="buy-outfit" href="#">Buy outfit</a>所以沒有被存儲。

  • 現在$('div.myframe:nth-child(3)')試圖抓住第三個孩子,這是一個.myframe,因爲它是如此<div class="myframe">它存儲。

替代

在你的情況jquery eq()選擇是比較合適的,它的偉大工程:

// select the first child  
$('div.myframe').eq(0); 
// instead of 
// $('div.myframe:nth-child(1)') 

附:EQ(N)只連接到僞選擇 - 類別計數, 不限於任何其他元素的子女