按顺序将元素附加到每个div

时间:2016-06-10 06:29:58

标签: javascript jquery html css

好吧,我尝试使用csshtml创建徽标,这是输出:

jsFiddle

现在我希望使用jquery进行此操作并动态创建所有div。这是我到目前为止所做的:

var count = 13;
var n = 0;

for(var i = 0; i < count; i++) {
    n++;
    $('<div class="LogoRow" id="LogoRow-'+n+'"></div>').appendTo('#Logo');
}

$('#Logo .LogoRow:nth-child(odd)').addClass('LogoRowLeft');
$('#Logo .LogoRow:nth-child(even)').addClass('LogoRowRight');

$('.LogoRow').each(function() {
    var count = 8;
    for(var i = 0; i < count; i++) {
        $(this).append('<span class="LogoTriangle"></span>');
    }
});

jsFiddle

我将LogoRow添加到#Logo,然后将8 LogoTriangle添加到每个LogoRow,但问题是它应该以不同的方式附加LogoTriangle,如下所示:

append 8 `LogoTriangle` to `LogoRow` nth child 1
append 7 `LogoTriangle` to `LogoRow` nth child 2 and 3
append 6 `LogoTriangle` to `LogoRow` nth child 4 and 5
append 5 `LogoTriangle` to `LogoRow` nth child 6 and 7
append 4 `LogoTriangle` to `LogoRow` nth child 8 and 9
append 3 `LogoTriangle` to `LogoRow` nth child 10 and 11
append 2 `LogoTriangle` to `LogoRow` nth child 12 and 13
append 1 `LogoTriangle` to `LogoRow` nth child 14 and 15

但我不知道如何将元素追加到另一个这样的元素。有什么建议吗?

2 个答案:

答案 0 :(得分:3)

将初始count设置为15以获得完整的三角形。

count = 8移到循环外部并更改条件以减小值,如下所示。

count = 8;
$('.LogoRow').each(function(k) {
  console.log(count);
  for (var i = 0; i < count; i++) {
    $(this).append('<span class="LogoTriangle"></span>');
  }
  if (k == 0 || (k > 0 && k % 2 == 0))
    count--;
});

DEMO

答案 1 :(得分:1)

或者你可以通过不那么简单但易于理解的方式来做到这一点:

var count = 15;
var n = 0;

for(var i = 0; i < count; i++){
n++;
$('<div class="LogoRow" id="LogoRow-'+n+'"></div>').appendTo('#Logo');
}

$('#Logo .LogoRow:nth-child(odd)').addClass('LogoRowLeft');
$('#Logo .LogoRow:nth-child(even)').addClass('LogoRowRight');

var appends = {
  1: 8,  2: 7,  3: 7,  4: 6,  5: 6,  6: 5,  7: 5,  
  8: 4,  9: 4,  10: 3,  11: 3,  12: 2,  13: 2,
  14: 1,  15: 1,
};
for(var i in appends){
if(appends.hasOwnProperty(i)){
console.log(i, appends[i]);
    for(var j = 0; j < appends[i]; j++){        
      $('#LogoRow-' + i).append('<span class="LogoTriangle"></span>');
    }
  }
}

https://jsfiddle.net/czc6bhgw/8/