2011-12-14 33 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)只连接到伪选择 - 类别计数, 不限于任何其他元素的子女