我有一个包含9个字符串的数组:
var boardBox = ['#box1',
'#box2',
'#box3',
'#box4',
'#box5',
'#box6',
'#box7',
'#box8',
'#box9'];
我想将每个ID附加到动态添加到DOM的9个DIV中,如下所示
for (var i = 0; i < 9; i++){
$( ".row" ).append( "<div class='col-md-4'></div>" );
}
是否附加了这样做的方法?我尝试过它并没有运行。我试过了
$( ".row" ).text(boardBox[i]).appendTo('<div></div>');
答案 0 :(得分:2)
您可以使用i
按索引访问数组元素,并将该值连接为您要追加到行的div的内容:
for (var i = 0; i < 9; i++){
$( ".row" ).append( "<div class='col-md-4' >" + boardBox[i] + "</div>" );
}
答案 1 :(得分:1)
您可以使用它来代替另一个for循环:
$.each(boardBox, function(i, id){ // get the each id here
$('<div>', {
id: id, // apply it here
class:"col-md-4",
text:"test div"
}).appendTo('.row'); // append element here.
});
答案 2 :(得分:1)
您可以使用 appendTo()
var boardBox = ['#box1',
'#box2',
'#box3',
'#box4',
'#box5',
'#box6',
'#box7',
'#box8',
'#box9'
];
boardBox.forEach(function(v) {
// iterating over array
$('<div/>', {
text: v,
id: v
})
// generating element with content and id as array value
.appendTo('.row');
// appendding div to '.row'
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class=row></div>
&#13;
答案 3 :(得分:1)
var boardBox = ['#box1',
'#box2',
'#box3',
'#box4',
'#box5',
'#box6',
'#box7',
'#box8',
'#box9'];
var html = '';
for (var i = 0; i < boardBox.length; i++) {
html += "<div id="+boardBox[i]+ " class='col-md-4'>"+boardBox[i]+"</div>"
}
$(".row").append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row"></div>