2015-09-28 47 views
-1

我有低於9個字符串的數組:如何追加在陣列ID來的DIV與JavaScript

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>'); 
+1

嘗試, 爲(VAR I = 0;我

」); } – syms

+1

你真的想在ID中使用'#',或者因爲它是你在數組中添加的ID – Tushar

回答

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>

+0

現在,隨着答案被接受,付出了一些努力來解釋它,因爲OP似乎是天真的 – Tushar

2

可以使用i通過索引來訪問數組元素並連接作爲要附加DIV的內容一行值:

for (var i = 0; i < 9; i++){ 
    $(".row").append("<div class='col-md-4' >" + boardBox[i] + "</div>"); 
} 
+0

你可以將'append'移動到'for'之外嗎,它可以節省8個DOM操作 – Tushar

+0

@Tushar : 怎麼來的?? op還需要在每次迭代中追加內容。 –

+0

'var str ='';對於(var i = 0; i <9; i ++){ str + =「

" + boardBox[i] + "
」; } $('。row')。append(str);' – Tushar

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. 
}); 
+0

你可以移動每個''外部的'appendTo',它會保存8個DOM操作 – Tushar

+2

@Tushar不會產生任何問題,因爲今天的瀏覽器太快了,這不是問題。 – Jai

+0

我不是在談論問題在這裏,我在談論_optimization_,如果OP想要添加100s的div如何 – Tushar

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' 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class=row></div>