我有一个名为'div. cloneframe '的div,我正在使用jquery.clone克隆它。它工作得很好,我克隆了所有我需要的,使用这个函数:
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个数字?我这边有什么问题吗?
my 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
从Jquery: nth-child()选择器:
<对于:n -child(n),计算所有子节点,无论它们是什么指定的元素只有在与选择器附加到伪类。eq(n)只表示选择器附加到伪类的计数,不限于的子类选择任何其他元素,并选择第(n+1)个元素(n从0开始)
解决方案/strong>
不管我的测试
$('div.myframe:nth-child(1)')
尝试查看div.myframe是否有第一个子元素,以及该元素是否有class="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">
,所以它存储它。
替代strong>
在你的情况下,jquery eq()选择器更合适,它工作得很好:
// select the first child
$('div.myframe').eq(0);
// instead of
// $('div.myframe:nth-child(1)')
使用:eq(n) ,只计算附加到伪类的选择器,不限于任何其他元素的子元素